The problem is if I want to update the other fields and not the image. It passes the validation and doesn't update any of the fields.
But if I update the image and other fields it updates. Or if i update the image it updates.
View:
<?php echo $form->labelEx($model,'pimg'); ?>
<?php echo $form->fileField($model, 'pimg',array('id'=>'imgInput',)); ?>
<?php echo $form->error($model,'pimg'); ?>
Controller:
public function actionEdit($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Product']))
{
$model->pimg=CUploadedFile::getInstance($model,'pimg');
$fileName=$model->pimg;
$model->attributes=$_POST['Product'];
if($model->save())
$model->pimg->saveAs('images/'.$fileName);
$this->redirect(array('display','id'=>$model->productid));
}
$this->render('edit',array('model'=>$model,));
}
Model rules:
array('name, category, model, brand, description, price', 'required'),
array('pimg', 'file','types'=>'jpg','on'=>'create', 'allowEmpty'=>false),
array('pimg', 'file','types'=>'jpg','on'=>'update', 'allowEmpty'=>true),
I think the problem is with the controller. I keep getting the error:
Fatal error: Call to a member function saveAs() on a non-object in D:\wamp\www\testfolder\protected\controllers\ProductController.php on line 147
line 147: $model->pimg->saveAs('images/'.$fileName);
Image appears but then image name from db doesn't appear next to the choose file button renders stating no file chosen.
Note that I am new to Yii, and am stuck with this.
The problem is in your
actionEdit
i.e herehere you should check if the image has been uploaded or not. what happens is that yii is unable to execute this line
$model->pimg->saveAs('images/'.$fileName);
as no image has been uploaded. so you need to wrap it inside a condition i.eso your final code should be something like this
Update 1 If you want that on update null should not be stored in your database then you can do this
and then where you are using this
add this else code