Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a scenario in Yii2? [duplicate]

Tags:

yii2

my model rules are like this

public function rules()
        {
            return [
                [['email','password'], 'required'],
                [['email'],'unique'],
                [['status','role_id','created_by', 'updated_by', 'is_deleted'], 'integer'],
                [['created_at', 'updated_at'], 'safe'],
                [['first_name', 'last_name', 'email', 'username','location','address','about_me'], 'string', 'max' => 200],
                [['phone'], 'string', 'max' => 100]
            ];
        }

while creating a new user i need email and password required, but during update i need only username required. how can i do this?

like image 938
Bloodhound Avatar asked Jun 29 '15 09:06

Bloodhound


1 Answers

First of all, it's better to add scenarios as constants to model instead of hardcoded strings, for example:

const SCENARIO_CREATE = 'create';

Then you can use it like this:

[['email','password'], 'required', 'on' => self::SCENARIO_CREATE],

Another way is to describe it in scenarios() method:

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_CREATE] = ['email', 'password'];

    return $scenarios;
}

That way you need to specify all safe attributes for each scenario.

Finally, don't forget to set needed scenario after creating new model instance.

$model = new User;
$model->scenario = User::SCENARIO_CREATE;
...

Official docs:

  • Scenarios
like image 65
arogachev Avatar answered Dec 25 '22 10:12

arogachev