在cakePHP页面顶部显示所有模型验证错误

时间:2012-07-24 11:58:16

标签: php cakephp cakephp-2.0

我是CakePHP的新手。当我使用Model Field Validations时,它会显示每个必填表单字段前面的错误消息。我想在表单顶部的div中显示它。我该如何实现它。提前致谢。 这是我的代码: 型号:

<?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;
        }
    }
}

用户视图:

<!--<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>

3 个答案:

答案 0 :(得分:9)

您可以从视图上的$this->validationErrors变量中获取所有验证错误。然后随意迭代它们并根据需要显示。它们将按模型组织,如下:

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

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

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

最后,您可以隐藏表单助手的自动错误消息,方法是使用CSS隐藏它们或将FormHelper默认值设置为不显示它们。

<强> CSS

.input.error {
  display: none;
}

视图中的

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

答案 1 :(得分:1)

jeremyharris示例很有意义,但是如果您不想为每个表单字段手动设置循环,可以试试这个:

$errors = '';
foreach($this->validationErrors as $assoc) {
    foreach ($assoc as $k => $v) {
        $errors .= $this->Html->tag('li', $v);  
    }
}
echo $this->Html->tag('ul', $errors);

因此,如果验证返回多个错误,输出将如下所示:

 - A username is required
 - A password is required

答案 2 :(得分:0)

尽管这是一篇很老的文章,但我也想在这里回答我的解决方案。

要获取模型验证错误,只需使用$model->getErrors();。这将返回包含字段key的错误数组。

示例

$errors = $user->getErrors();