我在 Yii2 中有一个控制器,它将 ActiveController 扩展为 RESTful,我可以使用 PUT 方法更新它.但是,我想将某些属性设置为不安全,因为我不希望它们可更新.
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.
大家还有什么建议吗?
推荐答案这个规则只是意味着可以大量分配属性(使用 Model::load()),但是,没有任何验证,并且在每种情况下也是如此.
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.
通过以下内容,您引入了一个更新"场景,并告诉验证引擎 first_name 和 last_name 应该可以大量分配并得到验证,但密码被排除在外.正如您所料.
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'], ]; }还重要的是,在调用 load() 或 save() 之前,在更新或创建时设置场景(在控制器中):
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();更多推荐
如何在 RESTful Yii2 中将属性设置为不安全?
发布评论