user1970557
user1970557

Reputation: 515

symfony1.4 - ajax form and validation

I'm trying to create a form in a jQuery Dialog to save some data using AJAX.

I'm currently displaying the form in the diaog, which is fine.

I have in my action:

  $this->folderForm = new FolderForm(array(),array('user_template'=>$user_template));

  if ($request->isXmlHttpRequest()) 
  {
    if($request->isMethod('post'))
    {
        $this->folderForm->bind($request->getParameter('folder'));
        if($this->folderForm->isValid())
        {
            $values = $this->folderForm->getValues();

        } 
    }
  }

The above seems to work fine.

The problem is, how would I post the form to the action and display the error messages if the form is invalid via AJAX?

Thanks

Upvotes: 0

Views: 1383

Answers (1)

antony
antony

Reputation: 2893

You can post the form using a json dataType and return a json response containing information about whether the form is valid or contains errors. I'll assume you're posting the form with jQuery since you're using the jQuery-UI.

E.g.

// apps\myApp\modules\myModule\actions\action.class.php
public function executeEdit(sfWebRequest $request)
{
    $this->folderForm = new FolderForm(array(), array('user_template' => $user_template));

    if ($request->isMethod(sfRequest::POST) && $request->isXmlHttpRequest()) {
        $this->folderForm->bind($request->getParameter($form->getName()));

        $response = array();
        if ($this->folderForm->isValid()) {
            $folder = $this->folderForm->save();

            $response['errors'] = array();
        } else {
            foreach ($this->folderForm->getErrors() as $name => $error) {
                $response['errors'][] = array(
                    'field' => $name,
                    'message' => $error->getMessage(),
                );
            }
        }

        $this->getResponse()->setContentType('application/json');

        return $this->renderText(json_encode($response));
    }
}

Then in your javascript

$.post('/myModule/edit/id/' + id, $('my-form').serialize(), function (j) {
   var length = j.errors.length;
   if (length) {
       for (var i = 0; i < length; i++) {
           console.log(j.errors[i]);
           // Show error
       }
   } else {
       // Show success notification
   }
}, 'json');

Upvotes: 1

Related Questions