How to set attributes as unsafe in RESTful Yii2?

2019-07-21 14:10发布

I have a controller in Yii2 that extends ActiveController to be RESTful and I can update it OK using the PUT method. However I would like to set some attributes as unsafe as I don't want them to be updatable.

Reading some different examples I thought I would be able to do something like this in the model's rules:

[['first_name','last_name','!password'], 'safe', 'on' => 'update'],

However this doesn't prevent password being updated.

So then I found the scenarios() method and thought this should work:

public function scenarios()
{
    return [
        'default' => ['*'], // Also tried without this line
        'update' => ['first_name','last_name','!password'],
    ];
}

But that prevents all attributes getting updated.

Does anyone have any other suggestions?

标签: rest yii2
1条回答
狗以群分
2楼-- · 2019-07-21 14:50

This rule would just mean that the attributes can be massivly assigned (using Model::load()), however, without any validation and also in each scenario.

[['first_name','last_name','password'], 'safe'],

But you can use here also e.g. 'string' instead of 'safe'. Then it is also used in each scenario but now with string validation.

With the following you introduce an 'update' scenario and you tell the Validation engine that first_name and last_name should be massively assignable and get validated, but password is excluded from that. Like you have expected.

public function scenarios()
{
    return [
        'update' => ['first_name','last_name','!password'],
    ];
}

Important is also that you set the scenario on update or creation (in the controller) before you call load() or save():

$model = ...
$model->scenario = 'update';
$model->load(...);
$model->save();
查看更多
登录 后发表回答