Custom scenarios in yii 2 with example

Custom scenarios in yii 2 with example
Reading Time: 3 minutes

First of all, we will try to understand why we need to implement scenarios. Suppose we have, three form, all the three form save the data in one table but in the form we want to apply different validations rules. So, we will create scenarios and we will call that scenario in the controller before saving the data.

Steps to create custom scenarios in Yii 2

Let’s take an example and try to understand.


we have three types of form and one model is used to save the data. The first form creates new  student record, the second one  update student record, the third one is change password. All the three form is interacting with one model student. We will apply different validation rules in all these forms.

when creating the record for the first time , we can use 'on'=>'create' scenario. You can apply custom scenarios for updating records and many other places. 'on'=>'create' and 'on'=>'update' scenarios are explained here

custom scenarios in yii 2

  1. This is our create form looks like. To apply validations , we will define rules in the model. All the validations will be applied in create form. To apply specific validation then we have to use ‘on'=>'create' scenario. below is our model code, I will explain the code for each form.

    In this code, We have defined public function scenarios() In this we have defined two scenarios, update, and change_password. We will call these scenarios when our update action and ChangePassword action will run in the controller. Let me show you code how to do this. Below is my update action code.
  2. Similarly, we have to do when we are saving the change password form data. Below is the code.

    In this way, we can create as many scenarios we want. Suppose we have the login form, then we can create login scenario and we can only validate email and password rules.

    After creating the scenario, we have to apply that scenario to the login action.

    This is the simple tutorial how to create custom scenarios in Yii 2. If you want to learn about proper form validations in Yii 2 using model then please read our previous article. If you find any issue in this tutorial then please comment.

One Comment on “Custom scenarios in yii 2 with example”

Leave a Reply

Your email address will not be published. Required fields are marked *