Yii Framework: AJAX form?

Donnie Thomas picture Donnie Thomas · Jul 10, 2011 · Viewed 8.5k times · Source

Ok, I need help with something that seems pretty straightforward but I just can't figure out.

I have a page in Yii into which I'm trying to embed an AJAX form. Let's call the page A. The form takes in a single value, and needs to validate and store it into the DB if it's alright.

So far, here's what I've figured out:

The form is in a view _form.php, which contains a CActiveForm and an ajaxSubmitButton which looks like this:

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

The form is called within another A's view like so:

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

In the controller's actionSomething, I'm doing the following:

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();

    }
  }
}

In Firebug, I do see that when an error is encountered, the response contains the entire partial rendered form again. However targetdiv is not getting updated with the updated form with the error messages.

I have a feeling I'm doing something wrong in actionController, but I can't figure out what. It would be helpful if I could see a full example of an AJAX submitted form as well.

Thanks!

Answer

interskh picture interskh · Oct 28, 2012

$model->getErrors() would give you all the errors for all attributes

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();
}

And then pass this into ajaxSubmitButton() ajax option, according to this post on Yii forum: http://www.yiichina.net/forum/index.php/topic/23236-extension-how-to-display-validation-errors-comming-from-ajax-validation/

'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');
   });
}