douhe4336 2016-02-24 10:15
浏览 179
已采纳

yii2更新验证规则

I have a model and validation rules for it:

class User extends ActiveRecord implements IdentityInterface
{
 ...
public function rules()
{
    return [
        [['username', 'password', 'email'], 'required', 'on' => 'insert'],
        [['password', 'email'], 'required', 'on' => 'update'],
    ]
}

Actually the code produces no validators. When I remove 'on' section, everything goes well.

Digging in official documentation and search thru The Web didn't help me to understand what is the issue, and why can't I have custom required fields sets for different actions.

  • 写回答

1条回答 默认 最新

  • dongzhong3688 2016-02-24 10:49
    关注

    The Scenario is not automaticaly setted by Yii2 ActiveReccoed. If you need a specific scenario you must create it and assign

    E.g. for update ...

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['update'] = ['password', 'email'];//Scenario Values Only Accepted
        return $scenarios;
    }
    

    Also you can set scenario in your actionUpdate

    public function actionUpdate($id)
    {
       $model = $this->findModel($id);
       $model->scenario = 'update';
      ........
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部