我试图通过控制器而不是模型中的条件使字段无效。
$this->Model->invalidate('check_out_reason', __('Please specify check out reason.', true));
以上内容无法使该字段无效。相反,我需要以下内容:
$this->Model->invalidate('Model.check_out_reason', __('Please specify check out reason.', true));
但是,如果我希望在“字段”本身($ this-> model-> validationErrors)中显示错误消息,则需要使用“check_out_reason”而不是“Model.check_out_reason”。这意味着,如果我希望在控制器中使输入无效,我无法将错误消息显示在字段中。
我可以知道这是CakePHP中的一个错误吗?
答案 0 :(得分:1)
我创建了一个名为“Invoices”的测试控制器,仅用于测试,我开发了以下功能
public function index(){
if (!empty($this->request->data)) {
$this->Invoice->invalidate('nombre', __('Please specify check out reason.'));
if ($this->Invoice->validates()) {
// it validated logic
if($this->Invoice->save($this->request->data)){
# everthing ok
} else {
# not saved
}
} else {
// didn't validate logic
$errors = $this->Invoice->validationErrors;
}
}
}
我觉得它对我有用
为您的字段“check_out_reason”更改字段“nombre”以使该功能适应您的代码
答案 1 :(得分:1)
我找到了一个从控制器手动无效的解决方法。在这个问题上经常阅读我发现save()函数没有考虑通过在控制器中调用的invalidate()函数设置的失效,但是(这非常重要)如果直接从模型函数调用beforeValidate ()它工作得很好。
所以我建议进入AppModel.php文件并创建下一个公共方法:
public $invalidatesFromController = array();
public function beforeValidate($options = array()) {
foreach($this->invalidatesFromController as $item){
$this->invalidate($item['fieldName'], $item['errorMessage'], true);
}
return parent::beforeValidate($options);
}
public function invalidateField($fieldName, $errorMessage){
$this->invalidatesFromController[] = array(
'fieldName' => $fieldName,
'errorMessage' => $errorMessage
);
}
之后,确保模型的beforeValidate()函数调用父项的一个:
public function beforeValidate($options = array()) {
return parent::beforeValidate($options);
}
在您的控制器中使字段无效使用下一行:
$this->MyModel->invalidateField('fieldName', "error message");
希望它有所帮助!对我而言,它正在发挥作用!