我需要一位Cakephp 2.2专家来帮助我。 我想使用以下'$ this-> data'进行更新:
array(
'Button' => array(
(int) 0 => array(
'id' => '1',
'on' => '0'
),
(int) 1 => array(
'id' => '2',
'on' => '0'
),
(int) 2 => array(
'id' => '3',
'on' => '1'
),
(int) 3 => array(
'id' => '4',
'on' => '1'
)
)
)
Button模型中的验证规则是:
public $validate = array(
'id'=>array(
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Module id can not be empty',
'on' => 'update'
),
'naturalNumber' => array(
'rule' => 'naturalNumber' ,
'message' => 'Module id is not integer',
'on' => 'update'
)
),
'name'=>array(
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Module name can not be empty',
'on' => 'create'
),
'alphaNumericWithSpaces' => array(
'rule' => array('custom', '/^[a-z0-9 ]*$/i') ,
'message' => 'Module category is not alphanumeric'
)
),
'type'=>array(
'notEmpty' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Module category can not be empty',
'on' => 'create'
),
'naturalNumber' => array(
'rule' => 'naturalNumber',
'message' => 'Module category is not integer'
)
),
'on'=>array(
'boolean' => array(
'rule' => 'boolean',
'message' => 'Module ON value is not boolean'
)
));
然后,在控制器中,我有以下代码:
if(!empty($this->data)) {
if($this->Button->saveAll($this->data)) {
debug ('Saved!');
}
else {
debug($this->Button->validationErrors);
}
}
问题是“saveAll()”未进行更新,并触发以下验证错误,即使我已经使用了on =>这些字段上的'create'仅在创建记录时触发:
array(
'name' => array(
(int) 0 => 'Module name can not be empty'
),
'type' => array(
(int) 0 => 'Module category can not be empty'
)
)
谢谢!
答案 0 :(得分:1)
只是为了让saveAll的机制不会妨碍,尝试使用save()和单个记录。使用CakePHP 2.2.4,CakeValidationSet :: validate()在查看'required'之前一定要检查'on'(通过$ rule-> skip())。该错误表明它正在尝试创建,而不是更新。
要保存许多Button记录,您可能需要尝试使用此$ data结构。也许还可以使用saveMany()
array(
(int) 0 => array(
'Button' => array(
'id' => '1',
'on' => '0'
)
)
(int) 1 => array(
'Button' => array(
'id' => '2',
'on' => '0'
)
),
(int) 2 => array(
'Button' => array(
'id' => '3',
'on' => '1'
)
),
(int) 3 => array(
'Button' => array(
'id' => '4',
'on' => '1'
)
)
)