Cakephp 3验证错误显示

时间:2016-02-01 14:29:04

标签: cakephp cakephp-3.0

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

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

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

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

1 个答案:

答案 0 :(得分:3)

您是否在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

相关问题