Symfony 1.1 Ajax Form Validation

Since Symfony 1.1 was released, I am working with it. I adept a existing Symfony 1.0 application to 1.1. This process is quite tricky and needs a lot of research to get the result that I want.

As I faced a problem with a form which I submit via an Ajax request, I found a pretty nice solution in doing this with Symfony 1.1.

public function executeSubmitaction($request) {
    $form   = new FoobarForm();
 
    // set the form to bound status with the submitted values
    $form->bind($request->getParameter('formvalues'));
 
    // validate all values
    if (!$form->isValid()) {
        $errors = array();
        foreach ($form->getErrorSchema() as $field => $error) {
            $errors[$field] = $error->getMessage();
        }
        $this->errors = $errors;
        return sfView::ERROR;
    }
 
    // do stuff if the form is valid
 
    return sfView::SUCCESS;
}


On the view-side I then have a javascript function which handles all the errors and I am using the serialized errors-array in the error-template to display the errors to the propriate divs.

4 thoughts on “Symfony 1.1 Ajax Form Validation

  1. Hi,
    Nice tip.

    but…when you do:

    foreach ($form->getErrorSchema() as $field => $error)
    {
    $errors[$field] = $error->getMessage();
    }

    If there is an extra field (I tried with firebug) symfony will throw an error because it won’t see any associated widget.

  2. Hi
    This is a very nice tip :). It saves alot of my times while i was struggling to do postvalidator in sfForm.

  3. Thanks for the excellent write-up.
    Is it possible for you to provide more details about how you displayed the errors in correct divs.

    Thanks a lot for the help!
    Pranjal

  4. @Pranjal: The display part is just some jQuery “magic”. You find decent information on that at the jQuery website and also some information on the symfony website itself.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">