Mar*_*bal 0 cakephp cakephp-3.0
我试图为表单中的每个错误输入一起显示错误消息。
例如:用户必须设置他的姓名、年龄和电子邮件,但他只设置了姓名。验证器在年龄字段的 notEmpty 规则上正确返回 false。但它总是返回一个错误,但我需要得到两个错误 - 第一个错误为空年龄字段,第二个错误为空电子邮件字段。
用户添加年龄并提交数据后,(邮件字段仍为空)验证器在电子邮件的 notEmpty 规则上返回错误。但我需要这个错误以及之前提交中的年龄错误。
如何将错误消息分组在一起?
您是否在 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");
}
?>
Run Code Online (Sandbox Code Playgroud)
现在,在您的控制器中,您需要编写以下内容:
//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"));
}
Run Code Online (Sandbox Code Playgroud)
希望这能解决您的问题。
和平!xD