【问题标题】:Disable validation in update form - CakePHP在更新表单中禁用验证 - CakePHP
【发布时间】:2014-06-03 16:58:14
【问题描述】:

我有一个用于注册和更新数据的表格。 它工作正常,但是当我更新数据时,模型验证返回 false,因为插入的值已经存在。

我有以下代码:

/* Validation Rule*/
public $validate = array(
    'unique' => array(
        'rule' => array('unique', 'field in the table'),
        'message' => 'The field cannot be empty.'
    )
    ...
)
/* Function that check if the value already exists */
public function unique($value, $field) {
    $check = $this->find('count', array(
        'recursive' => -1,
        'conditions' => array(
            $this->Alias.$field => $value
        )
    ));

    return $check == 0;
}

那么,我怎样才能禁用唯一规则,但保留其他规则?

【问题讨论】:

    标签: validation cakephp


    【解决方案1】:

    您可以在验证规则中添加on,并仅在create 上接受此验证:

    public $validate = array(
        'unique' => array(
            'rule' => array('unique', 'field in the table'),
            'message' => 'The field cannot be empty.',
            'on' => 'create'
        );
    );
    

    参考:

    【讨论】:

      【解决方案2】:

      您可以在从控制器更新数据之前即时删除验证。

        // Completely remove all rules for a field
         $this->validator()->remove('field in the table');
      
       // Remove 'unique' rule from field in the table
       $this->validator()->remove('field in the table', 'unique');
      

      Removing rules from the set

      【讨论】:

      • 我是我的登录功能,在继续进行身份验证之前,我正在根据模型验证用户名和密码。在这种情况下,“on”修饰符不起作用。即时删除验证是最好的方法。
      【解决方案3】:

      我在 cakephp 2.8 的 MyController 中使用了这个:

       $this->MyModel->validator()->remove('field_name');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        • 2012-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多