CakePHP 2.x:如何在没有模型的情况下手动设置validationErrors?

时间:2016-07-26 12:35:31

标签: php validation cakephp formhelper

在阅读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?

        }
    }
}

我们不能在这里使用模型......如何为没有模型的字段设置validationError?如何手动使来自此类表单的字段无效?

1 个答案:

答案 0 :(得分:1)

最简单的方法是直接将错误发送到视图:

$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
]);