if this site looks broken its because you're using an old-ass browser! seriously like 10 years old! get a better one!

Symfony: Ajax Forms and awesome errors

27/07/2009 Posted in symfony Posted by: admin

To get nice feeling forms we need them to be ajax. But I had trouble getting the validation to work because it would just return my error and not the form. My solution is to use some simple Symfony tricks that would really be quite obvious if you read the documentation.. which i happened to do (after a long time searching in the dark). First point, read the doc, its awesome.

 

Anyway, lets get to business. We have a form in a partial: (templates/_update.php)

 

< div id="update_container" >

< ?php
echo form_remote_tag(array(

'url' => 'item/update',

    'update' => array('success'=>'update_notice','failure'=>'update_container'),
    'script'=>true
  ));

echo $form;

?>
   
< input type="submit" value="Update" / >
< /div>

 

So we have a simple form, that will update a notice div if it succeeds and update the whole div if it fails.

 

In the action we only really need to do a little trick with the return code for the failure: (actions/update)

 

$updated_item = $request->getParameter('form');

// get the old model from the passed in id
$old_item = itemPeer::retrieveByPk($updated_item['id']);

if($old_item) // make sure it exists
{
  // create the form for it (create the db link)
  $form = new itemForm($old_item);
   // bind it to the posted info
  $form->bind($request->getParameter($form->getName()),$request->getFiles($form->getName()));

  // and make sure its all good.

  if($form->isValid()){
    $form->save();
    return $this->renderPartial('item/updateMessage');
  }
  else
  {

     // this is the special part:

    $this->getResponse()->setStatusCode(500);
    // else return the form with the errors intact
    return $this->renderPartial('item/update',array('form'=>$form));

  }

}



and thats it, the form is now ajax but will return errors until it is successfully validated.

Post a comment: