Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 form validation in Ajax

On certain pages I use forms within bootstrap modals. I submit the form with Ajax and it gets validated in the controller. The most users will fill in the form correctly but if a validation fails the form is re-rendered and got send back to the user. I don't like this at all, but I can't find a better way because I can't get access the validation errors of the fields. Does someone has a better approach to achieve validation errors send back in JSON?

like image 361
Pi Wi Avatar asked Dec 04 '13 14:12

Pi Wi


4 Answers

I created a function myself

public function getFormErrors(Form $form) {
    $errors = $form->getErrors();
    foreach ($form->all() as $child) {
        foreach ($child->getErrors() as $key => $error) {
            $template = $error->getMessageTemplate();
            $parameters = $error->getMessageParameters();

            foreach ($parameters as $var => $value) {
                $template = str_replace($var, $value, $template);
            }

            $errors[$child->getName()][] = $template;
        }
    }
    return $errors;
}
like image 177
Pi Wi Avatar answered Nov 05 '22 16:11

Pi Wi


if I understand right you have a form and you need to get the errors for each field separately. if so, have a look at \Symfony\Component\Form\Form::getErrorsAsString() & do smth of the kind:

function getFormErrors($form)
{
    $errors = array();

    // get the form errors
    foreach($form->getErrors() as $err)
    {
        // check if form is a root
        if($form->isRoot())
            $errors['__GLOBAL__'][] = $err->getMessage();
        else
            $errors[] = $err->getMessage();
    }

    // check if form has any children
    if($form->count() > 0)
    {
        // get errors from form child
        foreach ($form->getIterator() as $key => $child)
        {
            if($child_err = getFormErrors($child))
                $errors[$key] = $child_err;
        }
    }

    return $errors;
}
like image 35
Vera Avatar answered Nov 05 '22 15:11

Vera


I'd say that the cleanest solution is to implement JMSSerializerBundle (http://jmsyst.com/bundles/JMSSerializerBundle) which uses the following Class:

https://github.com/schmittjoh/serializer/blob/6bfebdcb21eb0e1eb04aa87a68e0b706193b1e2b/src/JMS/Serializer/Handler/FormErrorHandler.php

then in your controller:

        // ...
        if ($request->isXMLHttpRequest()) {
        $jsonResponse = new JsonResponse();

        $serializer = $this->container->get('jms_serializer');
        $form = $serializer->serialize($form, 'json');

        $data = array('success' => false,
                       'errorList' => $form);

        $jsonResponse->setData($data);

        return $jsonResponse;
    }
like image 42
Xavier13 Avatar answered Nov 05 '22 16:11

Xavier13


I just have the same problem Today !

I sent the form with ajax, and if my controller sent me not a json 'OK', the form is refresh with the new form sent by the controller, who contains errors. Data 'OK' is sent when form->isValid(), else it return the form render.

HTML :

<div class="form_area">
     <form id="myform" action.... >
           ...code form ...
     </form>
</div>

Controller Action:

use Symfony\Component\HttpFoundation\JsonResponse;

public function myEditAction(){
    .......
    if ( $request->getMethod() == 'POST' ) {
        $form->bind($request);

        if ($form->isValid()) {
            ... code whn valide ...
            if ( $request->isXmlHttpRequest() ) {
                return new JsonResponse('OK');
            }
        }
    }

    return $form;
}

JS:

$('#myform').on('submit',function(e){
            var formdata = $('#myform').serialize();
            var href = $(this).attr('action');
            $.ajax({
                type: "POST",
                url: href,
                data: formdata,
                cache: false,
                success: function(data){
                    if(data != "OK") {
                        $('.form_area').html(data);
                    } 
                },
                error: function(){},
                complete: function(){}
            });
            return false;
        });
like image 32
BENARD Patrick Avatar answered Nov 05 '22 16:11

BENARD Patrick