Uploading pic, make it not required.

Hi all, a small question from beginner.

I need to attach icon to product, I did pic uploads following instructions:

http://www.yiiframew…doc/cookbook/2/

all works fine, but i need to set icon-field NOT REQUIRED, I dont need to reupload pic on each row update.

There's a rules from Model.

public function rules()


{


	return array(


		array('name','length','max'=>255),


		array('icon', 'file', 'types'=>'jpg, gif, png'),


		array('name, price1, price2, is_published', 'required'),


		array('is_published, category_id', 'numerical', 'integerOnly'=>true),


		array('price1, price2', 'numerical'),


	);


}

A part from Controller

public function actionUpdate()


{


	$product=$this->loadProduct();


	if(isset($_POST['Product']))


	{


		$product->attributes=$_POST['Product'];

      $product->icon=CUploadedFile::getInstance($product, 'icon');

      if($product->save())

      {

        $product->icon->saveAs('uploads/'.$product->icon->getName());

			$this->redirect(array('show','id'=>$product->id));

      }

	}


	$this->render('update',array('product'=>$product));


}

Icon field not marked as required by red *, but on form save i got validation error:

Please fix the following input errors:

  • Icon cannot be blank.

Where I'm was wrong?

Thanks!

Set the file validator's "allowEmpty" to be true. Unlike other validators, the default value for this option in file validator is false.

Quote

Set the file validator's "allowEmpty" to be true. Unlike other validators, the default value for this option in file validator is false.

Thank you, it is became not required, but when I update record and did'n attach pic, existing file on disc deletes and column Icon set empty.

Is there any easy way to keep Icon untouched?

I do a check once the form is submitted which looks to see if a new image has been submit, if yes, then it uses the scenario that validates the images and other fields, if not then it uses the scenario that does not validate the image.

Chris

Can you be so kind and attach a code example :)

Hi,

Example of changing validation scenario for record with file upload field - attached below.



	public function actionUpdate()


	{


		$picture=$this->loadPicture();


		if(isset($_POST['Picture']))


		{


			$picture->attributes=$_POST['Picture'];


      $picture->file = CUploadedFile::getInstance($picture,'file');


      $attributes = null;


      /* if picture file is empty => validate all safe except file */


      if ($picture->file->getHasError())


        $attributes = array_diff($picture->safeAttributes(), array('file'));


			if($picture->save(true, $attributes))


      {


        if ($picture->file->getHasError())


          $picture->file->saveAs(Picture::getImagePath().$picture->file);


        $this->redirect(array('show','id'=>$picture->id));


      }


		}


		$this->render('update',array('picture'=>$picture));


	}





Regards !

This is sorta related to the original topic, How would I go about deleating the image when deleting it from the database?

Well, very easily :] sample below…



class Page extends CActiveRecord {


       ...


       ...


	protected function afterDelete()


	{


           if (is_file($path.$this->file))


               unlink($path.$this->file);           


	}


}


Treat afterDelete model function as a predefined trigger function run after successful delete action.

Cheers!

you can also try this when updating model with files

in actionUpdate()

$model->attributes=$_POST['model'];

$orig_model=model::model()->findbyPk($model->id);

if(!$rower->file_field && $orig_rower->file_field){

$rower->file_field=$orig_rower->file_field;

}

if($model->save())redirect…

basically u're using old value when there's no new one provided.

Let me share share my codes on how i approached the issue of:

  • not requiring upoad file

  • deleting the previous file




	public function actionUpdate($id)

	{


                    .

                    .

                    .

                    $model=$this->loadModel($id);


                    // Uncomment the following line if AJAX validation is needed

                    // $this->performAjaxValidation($model);


                    if(isset($_POST['User']))

                    {

                            if ($_FILES['User']['name']['image_path'] == "")

                                $_FILES['User']['name']['image_path'] = $model->image_path;

                            else

                            {

                                if ($_FILES['User']['name']['image_path'] != $model->image_path)

                                {

                                        $path = Yii::app()->basePath . '/../images/profiles/';

                                        if (is_file($path.$model->image_path))

                                        {                                            

                                            unlink($path.$model->image_path);

                                        }

                                }

                            }

                            

                            $model->attributes=$_POST['User'];

                            $CUploadedFileInstance = CUploadedFile::getInstance($model,'image_path');

                            

                            if (!is_null($CUploadedFileInstance))

                            {

                                $model->image_path=CUploadedFile::getInstance($model,'image_path');

                            }


                            if($model->save())

                            {                                

                                    if (!is_null($CUploadedFileInstance))

                                    {

                                        //dcj save image

                                        $model->image_path->saveAs(Yii::app()->basePath . '/../images/profiles/' . $model->image_path);

                                    }


                                    //dcj extract the username for the logging system

                                    $user = User::model()->findByPk($model->idx);

                                    .

                                    .

                                    .


                            }

                    }


                    $this->render('update',array(

                            'model'=>$model,

                    ));


	}