禁用更新表单中的验证 - CakePHP

3

我有一个表单用于注册和更新数据。它运行良好,但是当我更新数据时,模型验证返回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;
}

所以,我如何禁用唯一规则,但保留其他规则?
3个回答

6
你可以在你的验证规则中加入on,并只在create时接受此验证:
public $validate = array(
    'unique' => array(
        'rule' => array('unique', 'field in the table'),
        'message' => 'The field cannot be empty.',
        'on' => 'create'
    );
);

Reference:


4
您可以在从控制器更新数据之前动态地删除验证。
  // 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');

从集合中删除规则


在我的登录函数中,我会在进行身份验证之前根据模型验证用户名和密码。在这种情况下,“on”修饰符不起作用。动态移除验证是最好的方法。 - luizs81

1
我在CakePHP 2.8的MyController中使用了这个代码:


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接