我有一个模型和验证规则:
class User extends ActiveRecord implements IdentityInterface
{
...
public function rules()
{
return [
[['username', 'password', 'email'], 'required', 'on' => 'insert'],
[['password', 'email'], 'required', 'on' => 'update'],
]
}
实际上代码不产生验证器。当我删除“on”部分时,一切都会顺利。
挖掘官方文档并通过网络搜索并不能帮助我理解问题是什么,以及为什么我不能为不同的操作设置自定义必填字段。
场景不是由 Yii2 ActiveRecord 自动设置的。如果您需要特定场景,则必须创建它并在模型中分配。
例如更新...
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['update'] = ['password', 'email'];//Scenario Values Only Accepted
return $scenarios;
}
您也可以在actionUpdate中设置场景
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
........
}