Not required but is required !!

Hello for all,

I have a problem in logo. In rules i didn’t the logo required but when the logo empty i can’t doing the save or update.

So the logo must be not empty for save new registration or update it however is not required in rules!!!

Really i don’t understood why must be the logo not empty.


public $logo;


public function rules()

        {

                return array(


                        array('nom, active', 'required'),

                        array('nom', 'length', 'max'=>75),

                        array('description', 'length', 'max'=>120),

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

                        array('active','length','max'=>10),

                        array('id, nom, description, logo, active', 'safe', 'on'=>'search'),

                );

        }



It’s actually required because it’s validation rule is that it’s a file.

So if it’s empty, it isn’t a file.

How do you make it optional?

Well, maybe move the file field out of the model and into a CForm instead.

Then you can reference it from your model instead: logopath, f.ex.

Not sure if I understand the question correctly, but you could use the allowEmpty property on certain scenarios.

Matt

I used :


array('logo', 'file', 'types' => 'jpg,gif,png', 'allowEmpty' => true)

But i got error

However i did that for make it optional but i didn’t get the good result :

i used this condition in controller


public function actionCreate() {

       

        $model = new X;


     if (isset($_POST['X'])) {

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

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

         if ($model->save() and !empty($image)) {

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

                $this->redirect(array('view', 'id' => $model->id));

         } elseif ($model->save()) {


          $this->redirect(array('view', 'id' => $model->id));

           }

        }


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

            'model' => $model,

        ));

    }

What error did you get? it should work?




array("avatar", "file", "types" => "jpg, jpeg, gif, png", "allowEmpty" => true)



Works for me, no validation errors. However if you are talking about a PHP error then try this …




if(CUploadedFile::getInstance($user, "avatar") != null) $user->avatar = CUploadedFile::getInstance($user, "avatar");

if(CUploadedFile::getInstance($user, "avatar") != null) $user->avatar->saveAs(Yii::app()->params->uploaded_profile_image_path . $user->id . ".jpg");



Put this …




if(CUploadedFile::getInstance($user, "avatar") != null)



Before parts of your file uploading code.

Thanks for all and thank you JamesBarnsley. it works now