【问题标题】:Cakephp 3 validation errors displayCakephp 3 验证错误显示
【发布时间】:2016-05-10 01:15:12
【问题描述】:

我正在尝试为表单中的每个错误输入一起显示错误消息。

例如:用户必须设置他的姓名、年龄和电子邮件,但他只设置了姓名。验证器在年龄字段的 notEmpty 规则上正确返回 false。但它总是返回一个错误,但我需要得到两个错误 - 空年龄字段的第一个错误和空电子邮件字段的第二个错误。

用户添加年龄并提交数据后,(邮件字段仍然为空)验证器在电子邮件的 notEmpty 规则上返回错误。但是我需要这个错误以及之前提交的年龄错误。

如何将错误消息组合在一起?

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    你是否在Model/Table/UsersTable.php中设置了所有的验证规则?

    它应该看起来像这样。

       <?php
       //Model/Table/UsersTable.php
       namespace App\Model\Table;
       use Cake\ORM\Table;
       use Cake\Validation\Validator;
    
       class UsersTable extends Table{
    
            public function validationDefault(Validator $validator){
    
            $validator  =   new Validator();
    
            $validator
                ->notEmpty("username","Name cannot be empty.")
                ->requirePresence("name")
                ->notEmpty("username","Email cannot be empty.")
                ->requirePresence("email")
                ->notEmpty("username","Age cannot be empty.")
                ->requirePresence("age");
        }
      ?>
    

    现在,在您的控制器中,您需要编写以下内容:

       //UsersController.php
    
    
       public function add(){
    
            $user   =   $this->Users->newEntity();
    
            if($this->request->is("post")){
                $user   =   $this->Users->patchEntity($user, $this->request->data);
                if($this->Users->save($user)){
                    $this->Flash->success(__('User has been saved.'));
                    return $this->redirect(['controller' => 'users', 'action' => 'login']);
                }
    
                if($user->errors()){
                    $error_msg = [];
                    foreach( $user->errors() as $errors){
                        if(is_array($errors)){
                            foreach($errors as $error){
                                $error_msg[]    =   $error;
                            }
                        }else{
                            $error_msg[]    =   $errors;
                        }
                    }
    
                    if(!empty($error_msg)){
                        $this->Flash->error(
                            __("Please fix the following error(s):".implode("\n \r", $error_msg))
                        );
                    }
                }
    
            }
    
            $this->set(compact("user"));
    
        }
    

    希望这能解决您的问题。

    和平! xD

    【讨论】:

    • 如何在每个输入框下方显示错误信息?
    猜你喜欢
    • 2017-10-04
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多