Question

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.

Était-ce utile?

La solution

The problem is in your actionEdit i.e here

$model->pimg=CUploadedFile::getInstance($model,'pimg');     
         $fileName=$model->pimg;
          $model->attributes=$_POST['Product'];
        if($model->save())
        $model->pimg->saveAs('images/'.$fileName);

here 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.e

if(!empty($model->pimg))
{
$model->pimg->saveAs('images/'.$fileName);
}

so your final code should be something like this

$model->attributes=$_POST['Product'];
 $model->pimg=CUploadedFile::getInstance($model,'pimg');     
    if(!empty($model->pimg))
    {
     $fileName=$model->pimg->name;
                $model->pimg->saveAs('images/'.$fileName);
    }
if($model->save())
//render here 

Update 1 If you want that on update null should not be stored in your database then you can do this

$model=$this->loadModel($id);
$prevImage=$model->pimg;  //add this line

and then where you are using this

if(!empty($model->pimg))
{
$model->pimg->saveAs('images/'.$fileName);
}
else{
$model->pimg=$prevIMage;
}

add this else code

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top