postsrc
postsrc

Reputation: 752

Yii2: Different ways of declaring model scenarios?

I have some questions regarding Yii Scenario (this concept is pretty new to me)

If I have Post class which extends Model and have the following attributes

public $id;
public $title;
public $body;

CONST SCENARIO_SAVE = 'save';
CONST SCENARIO_UPDATE = 'update';

is

// Code 1
public function rules() {
    return [
            ['id', 'integer'],
            [['title', 'body'], 'string'],
            [['id', 'title', 'body'], 'required']
    ];
}

public function scenarios()
{
    return [
        self::SCENARIO_SAVE => ['id', 'title', 'body'],
        self::SCENARIO_UPDATE => ['title', 'body']
    ];
}

the same as

// Code 2
return [
        ['id', 'integer'],
        [['title', 'body'], 'string'],
        [['id', 'title', 'body'], 'required', 'on' => 'save'],
        [['title', 'body'], 'required', 'on' => 'update']
];

is code 1 and 2 the same thing?

will the 'id', 'title', ‘body’safe from mass assigned for both codes or should i specify ’safe’ rules for code 1?

Upvotes: 2

Views: 1329

Answers (1)

Boniface Jibendi
Boniface Jibendi

Reputation: 11

Code 1 and code 2 are not the same. You will need to specify all safe attributes for each scenario

> `// Code 1
public function rules() {
    return [
            ['id', 'integer'],
            [['title', 'body'], 'string'],
            [['id', 'title', 'body'], 'required']
    ];
}`

For code 1 All the three attributes id, title, body will be required during both create and update actions.

> `// Code 2
return [
        ['id', 'integer'],
        [['title', 'body'], 'string'],
        [['id', 'title', 'body'], 'required', 'on' => 'save'],
        [['title', 'body'], 'required', 'on' => 'update']
];`

For code 2 id, title, body will be required if you set the model scenario to save using $model->scenario='save';

When $model->scenario='update', title and body will be required.

Here is an example of how we set the scenario of a model.Assuming the Post class.

public function actionMyAction(){
    $model = new Post;
    $model->scenario = 'save';//changing the scenario which you want to use

    if ($model->load(\Yii::$app->request->post())){
       // the rest of your code here....

        if($model->save(true,$this->scenario)){
          //return true if all the attributes passed the validation rules
        } 
    }
}

Here are some few other links that can help you get started with Scenarios

http://www.yiiframework.com/doc-2.0/yii-base-model.html#scenarios%28%29-detail http://www.bsourcecode.com/yiiframework2/yii2-0-scenarios/

Upvotes: 1

Related Questions