2

好的,我需要一些看起来很简单的帮助,但我就是想不通。

我在 Yii 中有一个页面,我试图在其中嵌入 AJAX 表单。让我们调用页面 A。表单接受单个值,如果没问题,需要对其进行验证并将其存储到数据库中。

到目前为止,这是我想出的:

表单位于视图 _form.php 中,其中包含一个 CActiveForm 和一个 ajaxSubmitButton,如下所示:

<?php echo CHtml::ajaxSubmitButton('submit', $this->createUrl('/site/something'), array('update'=>'#targetdiv'));?> 

该表单在另一个 A 的视图中被调用,如下所示:

<?php echo $this->renderPartial('/site/_form', array('AModel'=>$model)); //Passing some info about A ?>

在控制器的 actionSomething 中,我正在执行以下操作:

if (Yii::app()->request->isAjaxRequest) {

  $model = new AJAXForm('submit');

  if (isset($_POST['AJAXForm'])) {

    $model->attributes = $_POST['AJAXForm'];

    if ($model->validate()) {
    //When data's valid, save to DB is working fine. This part is working perfectly.
    }
    else {
      //This is the part I'm confused about and that's not working

      /*Trying to render the form to get the error messages and summary displayed
      but nothing's showing */
      $this->renderPartial('/site/_form', array('AModel'=>$model));

      Yii::app()->end();

    }
  }
}

在 Firebug 中,我确实看到当遇到错误时,响应会再次包含整个部分呈现的表单。但是,targetdiv 没有使用带有错误消息的更新表单进行更新。

我感觉我在 actionController 中做错了什么,但我不知道是什么。如果我也能看到 AJAX 提交表单的完整示例,那将会很有帮助。

谢谢!

4

2 回答 2

1

$model->getErrors()会给你所有属性的所有错误

http://www.yiiframework.com/doc/api/1.1/CModel#getErrors-detail

if ($model->validate()) {
  //When data's valid, save to DB is working fine. This part is working perfectly.
  }
else {
  $errors = $model->getErrors();
  echo $errors;

  Yii::app()->end();
}

然后将其传递给ajaxSubmitButton()ajax 选项,根据 Yii 论坛上的这篇文章:http ://www.yiichina.net/forum/index.php/topic/23236-extension-how-to-display-validation-errors-comming-从ajax验证/

'success'=>"function(html) {
   if (html.indexOf('{')==0) {
        var e = jQuery.parseJSON(html);
        jQuery.each(e, function(key, value) {
        jQuery('#'+key+'_em_').show().html(value.toString());
        jQuery('#'+key).addClass('clsError');
        jQuery('label[for='+key+']').addClass('clsError');
   });
}
于 2012-10-28T18:07:57.477 回答
0

尝试将“dataType”添加到您的 ajaxSubmitButton 属性,例如:

array('type' =>'POST',
    'update' => '#targetdiv',
    'dataType' => 'html',
),

您可能想尝试传回一些基本文本以首先对其进行测试——如果您只是尝试显示错误消息,则可能不需要重新呈现表单。

于 2011-07-11T00:08:49.593 回答