CakePHP在使用$ model-> save()时验证规则并跳过其他规则

时间:2012-02-12 06:39:14

标签: validation cakephp cakephp-2.0

我正在使用CakePHP 2.0,我有一个模型,我在其上使用验证:

 var $validate = array(
    'title' => array(
        'unique_rule'=>array(
            'rule' => 'isUnique',
            'on' => 'create',
            'message' => 'This title has already been taken.'
        ),
        'required_rule'=>array(
            'required' => true,
            'allowEmpty' => false,
            'message' => 'The title field is required.'
        )
    )
 );

,在控制器中我有一个编辑操作,我使用$ model-> save()来保存来自$ this-> request->数据的日期,但它没有通过isUnique验证规则,尽管它是不是新的记录插入。 有没有办法指定它是现有记录,而不是新记录?

2 个答案:

答案 0 :(得分:2)

如果我的问题是正确的,你必须在调用$model->save();之前设置模型的ID,这样才能知道这是一个更新。

请参阅http://book.cakephp.org/2.0/en/models/saving-your-data.html

“创建或更新由模型的id字段控制。如果设置了$ Model-> id,则更新具有此主键的记录。否则创建新记录:”

<?php
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);

// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);

答案 1 :(得分:0)

您的验证数组错误,尚未为'required_rule'设置规则,可能会触发isUnique错误消息。

var $validate = array(
'title' => array(
    'unique_rule'=>array(
        'rule' => 'isUnique',
        'on' => 'create',
        'message' => 'This title has already been taken.',
        'last' => true
    ),
    'required_rule'=>array(
       'rule' => array('notEmpty'),             
        'message' => 'The title field is required.'
    )
)
);

还要记住,使用required=>true不会检查实际数据,它只希望字段存在于数据数组中,“”也被视为存在