CakePHP 2.x:如何在没有模型的情况下手动设置 validationErrors?
CakePHP 2.x: How to manually set validationErrors without a model?
阅读 cakePHP: how set error validation to input field manually in controller 后,我想知道如果我们使用没有模型的表单,如何从控制器显示 validationError?
例如,我们有一个视图 checkSomething.ctp
,其中包含一个我们可以提交的表单。
echo $this->Form->create(false); // If we put "SomeModel" here, it would work.
echo $this->Form->input("myField");
然后说我们在 /Home/CheckSomething/
。
class HomeController extends AppController{
public function CheckSomething(){
// So manually validate a field
if(strlen($this->request->data["myField"]) < 5){
// myField is not valid, so we need to show an error near that field
$this->SomeModel->invalidateField("myField", "You must enter at least 5 characters");
// How to do this?
}
}
}
我们不能在这里使用模型...如何为没有模型的字段设置验证错误?如何手动使来自此类表单的字段无效?
最简单的方法是直接将错误发送到视图:
$errors = [];
if (strlen($this->request->data["myField"]) < 5) {
$errors['myField'] = 'You must enter at least 5 characters';
}
$this->set('errors', $errors);
在您看来:
echo $this->Form->create(false);
echo $this->Form->input('myField', [
'error' => isset($errors['myField']) ? $errors['myField'] : false
]);
阅读 cakePHP: how set error validation to input field manually in controller 后,我想知道如果我们使用没有模型的表单,如何从控制器显示 validationError?
例如,我们有一个视图 checkSomething.ctp
,其中包含一个我们可以提交的表单。
echo $this->Form->create(false); // If we put "SomeModel" here, it would work.
echo $this->Form->input("myField");
然后说我们在 /Home/CheckSomething/
。
class HomeController extends AppController{
public function CheckSomething(){
// So manually validate a field
if(strlen($this->request->data["myField"]) < 5){
// myField is not valid, so we need to show an error near that field
$this->SomeModel->invalidateField("myField", "You must enter at least 5 characters");
// How to do this?
}
}
}
我们不能在这里使用模型...如何为没有模型的字段设置验证错误?如何手动使来自此类表单的字段无效?
最简单的方法是直接将错误发送到视图:
$errors = [];
if (strlen($this->request->data["myField"]) < 5) {
$errors['myField'] = 'You must enter at least 5 characters';
}
$this->set('errors', $errors);
在您看来:
echo $this->Form->create(false);
echo $this->Form->input('myField', [
'error' => isset($errors['myField']) ? $errors['myField'] : false
]);