6

我是 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
        )
    )
);

}

用户控制器.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>
4

3 回答 3

10

$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
));
于 2012-07-24T14:21:14.867 回答
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
于 2013-12-12T17:51:20.670 回答
0

虽然这是一个非常古老的帖子,但我也想在这里回答我的解决方案。

要获取模型验证错误,只需使用$model->getErrors();. 这将返回一个带有 field 的错误数组key

例子

$errors = $user->getErrors();
于 2019-07-16T07:21:37.997 回答