Yii2: failed to open stream: No such file or directory - php

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');

Related

View file after uploading

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]);

Unable to open file for reading [attachments/.jpg] using yii2

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;

Yii2 form field stays blank even when filled

I have an update form which works as expected with one exception - the review textarea doesn't wan't to pass through the validation rules. When i fill it and try to update the form i get Review field is empty (or sort of this). I can see this with var_dump($model->getErrors()) in the controller. The $_POST['Author']['review'] got the value that i gave it but can't save it in $model->review column.
I am using CKEditor. Tried without it but without success. Here is my controller:
public function actionUpdate($id)
{
$model = $this->findModel($id, true);
$settings = new Settings();
if ($model->load(Yii::$app->request->post())) {
var_dump($model->save());
var_dump($model->getErrors());die;
$languages = Lang::find()->all();
foreach ($languages as $language) {
if ($language->default != 1) {
$names = 'names_' . $language->url;
$varNames = Yii::$app->OutData->sanitize($model->$names);
$model->$names = $varNames;
$review = 'review_' . $language->url;
$varReview = Yii::$app->OutData->sanitize($model->$review);
$model->$review = $varReview;
$metaDesc = 'meta_desc_' . $language->url;
$varMetaDesc = Yii::$app->OutData->sanitize($model->$metaDesc);
$model->$metaDesc = $varMetaDesc;
$url = 'url_' . $language->url;
$varUrl = Yii::$app->OutData->sanitize($model->$url);
$model->$url = $varUrl;
$cBirth = 'country_birth_' . $language->url;
$varcBirth = Yii::$app->OutData->sanitize($model->$cBirth);
$model->$cBirth = $varcBirth;
}
else
{
$model->names = Yii::$app->OutData->sanitize($model->names);
$model->review = Yii::$app->OutData->sanitize($model->review);
$model->meta_desc = Yii::$app->OutData->sanitize($model->meta_desc);
$model->url= Yii::$app->OutData->sanitize($model->url);
$model->country_birth = Yii::$app->OutData->sanitize($model->country_birth);
}
}
//записване на изображенията + thumb
if (isset($_POST["Author"]["imageFiles"]) and ! empty($_POST["Author"]["imageFiles"])) {
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
if (isset($model->imageFiles) and count($model->imageFiles) > 0) {
foreach ($model->imageFiles as $key => $file) {
$parseProdTitle = MakeURL::parseImageName($model->names.'_'.$model->id);
$fileName = $parseProdTitle . '_' . $model->id . '.' . $file->extension;
$fileName = Yii::$app->translate->cyr_to_lat($fileName);
$model->filename = $fileName;
$model->update();
$pic = Yii::getAlias('#frontend/web') . '/authors/thumb-270/' . $fileName;
$pic2 = Yii::getAlias('#frontend/web') . '/authors/' . $fileName;
$file->saveAs(Yii::getAlias('#frontend/web') . '/authors/' . $fileName);
$image = file_get_contents(Yii::getAlias('#frontend/web') . '/authors/' . $fileName);
file_put_contents($pic, $image);
$model->resizeImg($pic);
$settings->compress($pic, $pic, 90);
$settings->compress($pic2, $pic2, 90);
}
}
}
$model->update();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
The part of the view with the review field:
echo '<div class="row">';
echo '<div class="col-sm-12">';
$textContent = 'review';
if (!$model->isNewRecord) {
$model->$textContent = OutData::showTXT($model->$textContent);
}
echo $form->field($model, 'review')->textArea();
echo "<script>
CKEDITOR.replace( 'Author[review]' );
</script>";
echo '</div>';
echo '</div>';
And finally the model rules:
public function rules()
{
$required = ['names', 'review', 'meta_desc', 'url', 'birthday', 'country_birth'];
return [
[$required, 'required'],
[['active', 'sort'], 'required'],
['names', 'string', 'max' => 255],
['country_birth', 'string', 'max' => 255],
['review', 'string'],
['homeslider_review', 'string'],
['meta_desc', 'string', 'max' => 170],
['url', 'string', 'max' => 60],
[['active', 'sort'], 'integer'],
[['filename'], 'string'],
];
}
All the other fields work in proper way. This is the only rebel. Thank you in advance!
In your code everything is ok.If u don't want to validate the model, Try this one in your controller where u r saving your form.
var_dump($model->save(false));
This will solve your problem

Yii2: How to execute sql query after model->save()

public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post())) {
$imageName = $model->first_name;
$mobile = $model->primary_mobile;
$type = $model->room_type;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension);
//save the path in the db column
$model->id_image = 'uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I need to execute query \Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute(); after the model->save();
same query working in actionupdate() but not in actioncreate(),
Is it possible with behaviours?
You could override afterSave method of ActiveRecord or create a trigger directly on db
Documentation: http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#afterSave%28%29-detail
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
// your code here
Yii::$app->db->createCommand(sprintf("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '%s'", $this->room_type))->execute();
}

update a record without removing the uploaded file in yii

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')

Categories