3

I am very new to Yii.

I have to apply image validation (.svg and .png allowed) only if user have selected the image.

  public function rules() {
        return [
            [['logo'], 'file', 'extensions'=>'svg, png'],
        ];
    }

When user select image it works fine. But on update form we have only name of file. Now if we submit the form it will apply validation. I need validation only if user changes the image.

My Controller code

if ($model->load(Yii::$app->request->post())) {
            $model->logo = UploadedFile::getInstance($model, 'logo');
            if (!empty($model->logo)) {
                $model->logo->name = $model->logo->baseName . Yii::$app->formatter->asTimestamp(date('Y-d-m h:i:s')) . '.' . $model->logo->extension;
                $logoPath = Yii::getAlias('@common') . '/web/uploads/logo/' . $model->logo->name;
                $model->logo->saveAs($logoPath, false);
            }
            if ($model->updateSite()) {
                return $this->redirect(['site-list']);
            }
        }

Please let me know if you need more clarification. Thanks.

1

1 Answer 1

2

Using scenarios may be helpful in this case.

Define validation rules to dependend on scenario

public function rules() {
    return [
        [['logo'], 'file', 'extensions'=>'svg, png', 'on' => 'imageUploaded'],
    ];
}

Then define scenario for model in controller. Something like this.

if ($model->load(Yii::$app->request->post())) {
        $model->logo = UploadedFile::getInstance($model, 'logo');
        if (!empty($model->logo)) {
           $model->scenario = 'imageUploaded';
           ...
        }
    }

It's also possible to define anonymous function for conditional validation.

public function rules() {
    return [
        [['logo'], 'file', 'extensions'=>'svg, png', 'when' => function ($model) {
             //return true to apply the rule
             return $model->isImageUploaded();
        }],
    ];
}

More on rules and scenarios can be found here https://github.com/yiisoft/yii2/blob/master/docs/guide/input-validation.md#declaring-rules-

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.