Saving and validating only changed (dirty) values on Yii2

Let’s say, your username is: user1. And we want to change password (only!).

In User model if we have rule like below:

[['username', 'email'], 'unique'],

then we have a big problem.

In case you want to change your password and leave all other form fields as they are, this configuration configuration will give error like: user1 is not unique which is pretty weird.

What I want to achieve is, to validate only if actual values are changed. And I need this only for my Update action. Because, [['username', 'email'], 'unique']  covers Create action pretty well

So here is my solution:
By the way, I used scenarios for my solution.

Step 1: Seperated Create and Update using scenarios

I added following rules to my Usermodel:

[ ['username', 'email'], 'unique', 'when' => function ($model, $attribute) { return $model->{$attribute} !== $model->getOldAttribute($attribute); }, 'on' => 'update' ], [ ['username', 'email'], 'unique', 'on' => 'signup' ],

Step 2: Made changes on update action

In my Update action I added

public function actionUpdate() { $model = $this->findModel(Yii::$app->user->id); $model->scenario = "update"; ... }

Step 3: Made changes on Create action

$model = new User(['scenario' => 'signup']);

Voila!

Now it works, as I wanted!

Tural Aliyev

I'm traveloholic, musicphile, technoholic, cinephile, workaholic software developer

Istanbul http://tural.us

Subscribe to Tural's Notebook

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!