【问题标题】:how to use required on insert validator for yii2?如何在 yii2 的插入验证器上使用 required ?
【发布时间】:2015-03-11 07:45:03
【问题描述】:

谁能对如何在 yii2 中使用"on" => "insert" 验证提出建议? 我用过

array('field_name', 'required', 'on'=>'insert')

在 Yii1 但在 yii2 它不检查我是否设置了

['field_name', 'required', 'on'=>'insert']

。 你能解释一下这里有什么问题吗? 提前致谢。

【问题讨论】:

    标签: yii yii2


    【解决方案1】:

    您应该在验证之前简单地设置模型的场景:

    $model->scenario = 'insert';
    

    从 Yii2 开始:

    默认情况下,一个模型只支持一个名为default的场景

    阅读更多:http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios

    【讨论】:

      【解决方案2】:

      首先定义场景:

      // scenario is set as a property
      $model->scenario = 'insert';
      

      或

      // scenario is set through configuration
      $model = new User(['scenario' => 'insert']);
      

      那么你可以将规则指定为:

      // for single field
      ['field_name', 'required', 'on' => 'insert'],
      
      // for multiple fields
      [['field_name1','field_name2'], 'required', 'on' => 'insert'],
      

      更多详情请查看:http://www.yiiframework.com/doc-2.0/guide-structure-models.html#validation-rules

      【讨论】:

        猜你喜欢
        • 2015-04-29
        • 2013-09-17
        • 1970-01-01
        • 1970-01-01
        • 2016-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多