This program is an Email with attachment , but when I try to click submit button it say.
Swift_IoException
Unable to open file for reading [attachments/.jpg]
Here is my EmailController.php Code
public function actionCreate()
{
$model = new emails();
if ($model->load(Yii::$app->request->post()))
{
$model->attachment=UploadedFile::getInstance($model,'attachment');
if($model->attachment)
{
$time=time();
$model->attachment->saveAs('attachments/'.$time.'.'.$model->attachment->extension);
$model->attachment='attachments/'.'.'.$model->attachment->extension;
}
if($model->attachment)
{
$value=Yii::$app->mailer->compose()
->setFrom([ 'rodulfoalmeda#gmail.com'=>'Sample' ])//->setFrom([ $company->company_email=>$company->company_name ])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->attach($model->attachment)
->send();
}else
{
$value=Yii::$app->mailer->compose()
->setFrom([ 'rodulfoalmeda#gmail.com'=>'Sample' ])//->setFrom([ $company->company_email=>$company->company_name ])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->send();
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
You are ommiting $time in assigning to $model->attachment property.
$time = time();
$path = 'attachments/' . $time . '.' . $model->attachment->extension;
$model->attachment->saveAs($path);
$model->attachment = $path;
Related
like I have a view index.php(Gridview)- linked to a Menu Manage Instructor.
from there I click on edit for a specific instructor.
The URL I get is like:
admin/user/update-instructor?id=11
In this page I have multiple tabs, one tab is instructor_schedule, which is again a grid view with add records button on top.
I can add records clicking on add record without any issue.
My problem is now I want the form page redirect back to the page
admin/user/update-instructor?id=11
How I can achieve that?
I have tried like:
return $this->redirect(['user/update-instructor','id' => $model->id]);
and
return $this->redirect(['user/update-instructor','id' => $model->instructor_id]);
but I am getting the error missing information id.
Thanks.
action Create(ClassDurationController):
public function actionCreate() {
$model = new ClassDuration();
$count = count(Yii::$app->request->post('ClassDuration', []));
$classdurations[] =new ClassDuration();
for($i = 1; $i < $count; $i++) {
$classdurations[] = new ClassDuration();
}
//if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Model::loadMultiple($classdurations, Yii::$app->request->post()) && Model::validateMultiple($classdurations)) {
foreach ($classdurations as $classduration) {
// var_dump($classdurations);
$classduration->instructor_id=$_POST['ClassDuration'][0]['instructor_id'];
$classduration->save(false);
}
Yii::$app->getSession()->setFlash('successClass');
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['user/update-instructor','id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'classdurations' => $classdurations,
]);
}
Action Update(ClassDurationController):
public function actionUpdate($id,$tab='information') {
$model = $this->findModel($id);
$wd_instructor = ClassDuration::find('instructor_id')->where(['id'=>$id])->One();
$wd_instructor_id = $wd_instructor->instructor_id;
$classdurations = ClassDuration::find()->where(['instructor_id'=>$wd_instructor_id])->all();
if (Model::loadMultiple($classdurations, Yii::$app->request->post()) && Model::validateMultiple($classdurations)) {
foreach($classdurations as $classduration){
$classduration->location_id=$_POST['ClassDuration'][0]['location_id'];
$classduration->save(false);
}
Yii::$app->getSession()->setFlash('successClass');
// return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['user/update-instructor', 'id' => $model->instructor_id, 'tab' => 'instructor_schedule']);
}
return $this->render('update', [
'model' => $model,
'workingdays' => $classdurations,
]);
}
ActionUpdateInstructor:
public function actionUpdateInstructor($id,$tab='information') {
$model = User::findOne($id);
$uploadPath = 'web/instructor/' . $id;
if (!file_exists($uploadPath)) {
mkdir($uploadPath);
}
$profile = Instructor::find()->where(['user_id' => $id])->one();
if ($profile) {
$instructor_profile = $profile;
} else {
$instructor_profile = new Instructor;
$instructor_profile->user_id = $id;
}
if ($id == 1) {
$cls = 'hide';
} else {
$cls = '';
}
$title = "Update";
$modelsRest = $model->rest;
$modelsBreakTime = $model->breakTime;
if (Yii::$app->request->isAjax && $model->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($model);
}
if (Yii::$app->request->isAjax && $instructor_profile->load($_POST)) {
Yii::$app->response->format = 'json';
return \yii\bootstrap\ActiveForm::validate($instructor_profile);
}
if ($model->load(Yii::$app->request->post()) && $instructor_profile->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsRest, 'id', 'id');
$modelsRest = Model::createMultiple(RestDays::classname(), $modelsRest);
Model::loadMultiple($modelsRest, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsRest, 'id', 'id')));
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsRest),
ActiveForm::validate($model),
ActiveForm::validate($instructor_profile)
);
}
if (trim($model->password) != '') {
$model->setPassword($model->password);
}
$model->username = $model->email;
$model->save();
if ($model->user_role != '') {
$assign = AuthAssignment::find()->where(['user_id' => $model->id])->One();
$assign->item_name = $model->user_role;
$assign->save();
}
$instructor_profile->file = UploadedFile::getInstance($instructor_profile, 'file');
$instructor_profile->user_id = $model->id;
if ($instructor_profile->file != '') {
$instructor_profile->instructor_image = time() . '.' . $instructor_profile->file->extension;
}
$instructor_profile->save(false);
if ($instructor_profile->file != '') {
$uploadPath = 'web/instructor/' . $instructor_profile->user_id;
if (!file_exists($uploadPath)) {
mkdir($uploadPath);
}
$instructor_profile->file->saveAs($uploadPath . '/' . $instructor_profile->instructor_image);
}
$valid = $model->validate();
$valid = Model::validateMultiple($modelsRest) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (!empty($deletedIDs)) {
RestDays::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsRest as $modelRests) {
$modelRests->instructor_id = $model->id;
if (!empty($modelRests->from_date) && !($flag = $modelRests->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
//return $this->redirect(['view-instructor', 'id' => $model->id]);
return $this->redirect(['instructor']);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('update_instructor', [
'model' => $model,
'modelsRest' => (empty($modelsRest)) ? [new RestDays] : $modelsRest,
'instructor_profile' => $instructor_profile,
'title' => $title,
'cls' => $cls,
]);
}
In your action Create(ClassDurationController) you assign to $model only
$model = new ClassDuration();
Maybe you should insert another variable to get id from parent or
return $this->redirect(['user/update-instructor','id' => $_POST['ClassDuration'][0]['instructor_id']]);
I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
How can I redirect the user to a view page after uploading file?
Now it works only when I write id of db entry in view
I'm totally new to php and yii 2.
Controller
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file && $model->validate()) {
$postFile = Yii::$app->request->post();
$directory = Yii::getAlias('#frontend/web/uploads');
$uid = Yii::$app->security->generateRandomString(6);
$fileName = $uid . '.' . $model->file->extension;
$filePath = $directory . '/' . $fileName;
$path = 'http://frontend.dev/uploads/' . $fileName;
$userinfo = new webminfo();
$userinfo->uid = $uid;
$userinfo->author_id = Yii::$app->user->id;
$userinfo->path = $filePath;
$userinfo->url = $path;
$userinfo->created_at = time();
$userinfo->ip = Yii::$app->getRequest()->getUserIP();
$userinfo->save();
if ($model->file->saveAs($filePath)) {
Yii::$app->session->setFlash('success', 'Success');
return $this->redirect(['view', 'id' => $userinfo->uid]);
}
}
else {
Yii::$app->session->setFlash('error', 'Error');
}
}
return $this->render('upload', ['model' => $model]);
}
public function actionView($id) {
$model = new webminfo();
return $this->render('view', [
'id' => $id,
'model' => $model,
]);
}
View
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
use app\models\webminfo;
$this->title = 'View';
$this->params['breadcrumbs'][] = $this->title;
?>
Use $uid instead of $userinfo->uid as follows in your redirect function
return $this->redirect(['view', 'id' => $uid]);
i have problem with my upload/update function in Yii2 framework.
My update function:
public function actionUpdate($id) {
$model = $this->findModel($id);
// $model->scenario = 'update';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$uploadDir = Yii::getAlias('#web/web/uploads') . Yii::getAlias('#web/web/uploads');
$uploadPath = Yii::getAlias('#web/web/uploads');
$model->save();
$imageProject = $model->id;
//Main Image
$image = UploadedFile::getInstance($model, 'main_image');
if ($image) {
$imgProject = 'project_' . $imageProject . '.' . $image->getExtension();
$image->saveAs($uploadDir . '/' . $imgProject);
$model->main_image = $uploadPath . '/' . $imgProject;
}
if ($model->upload()) {
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
And my params.php file :
return [
'aliases' => [
'#projectImgPath' => '#webroot/web/uploads',
'#projectImgUrl' => '#web/web/'
]
];
When i upload file in my form i have this error:
move_uploaded_file(/web/uploads/web/uploads/gallery_1_3.png): failed to open stream: No such file or directory
Anyone can help me... thank`s !
$uploadDir = Yii::getAlias('#web/web/uploads') . Yii::getAlias('#web/web/uploads');
replace with
$uploadDir = Yii::getAlias('#web/web/uploads');
I need to UPDATE record with out changing or deleting filename(i mean file) , OR reinsert file again so how i can do this?
here is my actionCreate, How i can write update?
public function actionCreate() {
$model = new Page;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save()) {
if ($model->filename !== null) {
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
So Please can anyone find a solution
If you don't need to change or delete filename in edit/update then ignore filename (and upload part) assuming the file is alrready uploaded and you don't wish to change/delete it.
public function actionUpdate($id) {
$model = $this->loadModel($id);
$file = $model->filename;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = $file;
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
Try this, it's working for me -
create a upload folder outside protected directory and also give read/write permission.
actionCreate function -
public function actionCreate() {
$model = new Page();
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if(!empty( $fileName)){
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias('application') . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
if(!$model->hasErrors() && $model->validate() && $model->save(false)) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'success'));
}
}
}
actionUpdate function -
public function actionUpdate() {
$model = Page::model()->findbyPK($id);
$model->scenario = 'update';
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
if(empty($_POST['Page']['filename'])) { $file_name = $model->filename; } //store existing file name into a variable if your uploading a file on update
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if($model->validate()) {
if(!empty($fileName)) {
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias( 'application' ) . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
else {
$model->filename = $file_name; //allow existing file name
}
if( !$model->hasErrors() && $model->save(false) ) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'update'));
}
}
}
In model rules array define this -
array('filename', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')