在cakePHP的页面顶部显示所有模型验证错误 [英] Show all model validation errors on top of the page in cakePHP

查看:256
本文介绍了在cakePHP的页面顶部显示所有模型验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是CakePHP的新手。当我使用模型字段验证时,它显示每个必填表单字段的错误消息infront。我想显示在窗体的顶部的div。如何实现它。提前致谢。
这是我的代码:
模型:

 <?php 
类用户extends AppModel {
public $ validate = array(
'username'=> array(
'required'=> array(
'rule'=> array('notEmpty '),
'message'=>'需要用户名'
),
数组(
'rule'=> array('minLength',8)
'message'=>'用户名必须至少为6个字符'

),
'password'=> array(
'required' => array(
'rule'=> array('notEmpty'),
'message'=>'需要密码'

) b $ b'city'=> array(
'required'=> array(
'rule'=> array('notEmpty'),
'message'=& 'A City is required'

),
'state'=> array(
'required'=> array(
'rule'=> ; array('notEmpty'),
'message'=> 'A state is required'

),
'role'=> array(
'valid'=> array(
'rule'=> array('inList',array('admin','author')),
'message'= >'请输入有效的角色',
'allowEmpty'=> false


);

}

UsersController.php

  public function add(){
$ this-> set('states_options',$ this-> State-& ,array('fields'=> array('id','name'))));
$ this-> set('cities_options',array());
if($ this-> request-> is('post')){
$ this-> User-> set($ this-> request-> data);
if($ this-> User-> validates())
{
$ this-> User-> create
if($ this-> User-> save($ this-> request-> data)){
$ this-> Session-> setFlash(__已保存));
$ this-> redirect(array('action'=>'index'));
} else {
$ this-> Session-> setFlash(__('无法保存用户,请重试。
}
}
else {
$ errors = $ this-> User-> validationErrors;
$ this-> set('ValidateAjay',$ errors);
// pr($ errors); die;
}
}
}

用户视图:

 <! - < script src =http://code.jquery.com/jquery-1.7.2.js >< / script>  - > 
< script>
$(document).ready(function(){
$('#UserState')。change(function(){
var stateid = $(this).val();
$ .ajax({
type:POST,
url:checkcity,
data:'stateid ='+ stateid +'& part = checkcity',
success:function(data){
$(#city_div)。html(data);
}
});
});
} );
< / script>
< div class =users form>
<?php
if(!empty($ ValidateAjay)){
pr($ ValidateAjay);
}
echo $ this-> Form-> create('User'); ?>
< fieldset>
< legend><?php echo __('Add User'); ?>< / legend>
<?php
echo $ this-> Form-> input('username');
echo $ this-> Form-> input('password');
echo $ this-> Form-> input('state',array('options'=> $ states_options,'empty'=>'Select State'));
?>
< div id =city_div>
<?php
echo $ this-> Form-> input('city',array('options'=> $ cities_options,'empty'=>'Select City') );
?>
< / div>
<?php
echo $ this-> Form-> input('role',array(
'options'=> array('admin'=>'Admin ','author'=>'Author')
));
?>
< / fieldset>
<?php echo $ this-> Form-> end(__('Submit')); ?>
< / div>


解决方案

$ c> $ this-> validationErrors 变量。然后随意循环遍历他们,并显示你喜欢。它们将按模型组织,如下所示:

 数组(
'User'=& $ b'username'=>'此字段不能为空。',
'password'=>'此字段不能为空。'

);

然后你可以在视图上遍历它们,并显示它们。此示例将它们显示为无序列表:

  $ errors =''; 
foreach($ this-> validationErrors ['User'] as $ validationError){
$ errors。= $ this-> Html-> tag('li',$ validationError);
}
echo $ this-> Html-> tag('ul',$ errors);



最后,您可以通过使用CSS隐藏表单助手的自动错误消息或设置FormHelper默认值

 <$ c $ 

c> .input.error {
display:none;
}



在视图中

  $ this-> inputDefaults(array(
'error'=> false
));


I am new to CakePHP. When I am using Model Field Validations then it is showing error message infront of each required form field. I want to show it in a div at the top of the form. How I can implement it. Thanks in advance. Here is my Code: Model:

<?php
class User extends AppModel {
public $validate = array(
    'username' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A username is required'
        ),
     array(
    'rule'    => array('minLength', 8),
    'message' => 'Username must be at least 6 characters long'
     )
    ),
    'password' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A password is required'
        )
    ),
     'city' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A City is required'
        )
    ),
     'state' => array(
        'required' => array(
            'rule' => array('notEmpty'),
            'message' => 'A State is required'
        )
    ),
    'role' => array(
        'valid' => array(
            'rule' => array('inList', array('admin', 'author')),
            'message' => 'Please enter a valid role',
            'allowEmpty' => false
        )
    )
);

}

UsersController.php

public function add() {
    $this->set('states_options', $this->State->find('list', array('fields' =>array('id','name') )));
        $this->set('cities_options', array());
    if ($this->request->is('post')) {
        $this->User->set($this->request->data);
        if($this->User->validates())
        {
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('The user has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
        }
     }
     else {
        $errors = $this->User->validationErrors;
            $this->set('ValidateAjay',$errors);             
        //pr($errors);die;
        }
    }
}

User View:

<!--<script src="http://code.jquery.com/jquery-1.7.2.js"></script>-->
<script>
$(document).ready(function(){
$('#UserState').change(function(){
  var stateid=$(this).val();
  $.ajax({
  type: "POST",
  url: "checkcity",
  data:'stateid='+stateid+'&part=checkcity',
  success: function(data) {
  $("#city_div").html(data);
  }
  });
});
});
</script>
<div class="users form">
<?php
 if(!empty($ValidateAjay)){
 pr($ValidateAjay);
 }
 echo $this->Form->create('User'); ?>
 <fieldset>
    <legend><?php echo __('Add User'); ?></legend>
<?php
    echo $this->Form->input('username');
    echo $this->Form->input('password');
    echo $this->Form->input('state', array('options' => $states_options , 'empty' => 'Select State'  ));    
    ?>
   <div id="city_div">
   <?php
    echo $this->Form->input('city', array('options' => $cities_options, 'empty' => 'Select City' ));
    ?>
    </div>
   <?php
    echo $this->Form->input('role', array(
        'options' => array('admin' => 'Admin', 'author' => 'Author')
    ));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
 </div>

解决方案

You can get all validation errors from the $this->validationErrors variable on the view. Then feel free to iterate through them and display as you like. They will be organized by model, like so:

array(
  'User' => array(
    'username' => 'This field cannot be empty.',
    'password' => 'This field cannot be empty.'
  )
);

Then you can iterate through them on the view and display them as such. This example displays them as an unordered list:

$errors = '';
foreach ($this->validationErrors['User'] as $validationError) {
  $errors .= $this->Html->tag('li', $validationError);
}
echo $this->Html->tag('ul', $errors);

Lastly, you can hide the form helper's automatic error messages by hiding them with CSS or setting the FormHelper defaults to not show them.

CSS

.input.error {
  display: none;
}

or

in the view

$this->Form->inputDefaults(array(
  'error' => false
));

这篇关于在cakePHP的页面顶部显示所有模型验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆