Ravioli87
Ravioli87

Reputation: 835

Symfony2 Form Validation Error Returning HTTP Code '200'

Upon submitting an invalid form via HTTP POST, I expect my Symfony REST service (using FOSRestBundle) to return a 400 Bad Request code. Instead, it is returning 200 OK even though it is returning the errors in JSON format like I want.

Within my entity, I am using

Symfony\Component\Validator\Constraints as Assert;

to ensure no blank entries are given for any of the fields. For example:

/**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=255)
 * @Assert\NotBlank()
 */
private $title;

Here is my controller method:

public function postAvrequestAction(Request $request){
    $entity = new AvRequest();

    $form = $this->get('form.factory')->createNamed('', new AvRequestType(), $entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        $serializer = $this->get('serializer');
        $serialized = $serializer->serialize($entity, 'json');

        return new Response($serialized, 201);
    }

    return new JsonResponse(array(
        'errors' => $this->getFormErrors($form, 400)
    ));

And here is my HTML form with AJAX code upon submission:

       <form id="postform" role="form" method="POST" action="http://localhost:8000/api/avrequests">
            Title: <input type="text" name="title" id="title"/>
            Request Date: <input type="text" name="requestDate" id="requestDate"/>
            Deliver Date: <input type="text" name="deliverDate" id="deliverDate"/>
            Return Date: <input type="text" name="returnDate" id="returnDate"/>
            <input type="submit" class="button" value="Submit Request" />
        </form>
        <script>
            <!--
            $(document).ready(function(){
                $('#postform').validate({
                    debug: true,
                    rules: {
                        ...
                    },
                    messages: {
                        ...
                    },
                    submitHandler: function(form){
                        event.preventDefault();

                        ajaxObject = {
                            url: $("#postform").attr("action"),
                            type: 'POST', // Can be GET, PUT, POST or DELETE only
                            dataType: 'json',
                            xhrFields: {
                                withCredentials: true
                            },
                            crossDomain: true,
                            contentType: "application/json; charset=UTF-8",
                            data: JSON.stringify({"title":$("#title").val(), "requestDate":$("#requestDate").val(), "deliverDate":$("#deliverDate").val(), "returnDate":$("#returnDate").val()})
                        };

                        $.ajax(ajaxObject)
                            .done(function(data,status,xhr) {
                                console.log( status );
                                $(':input','#postform').not(':button, :submit, :reset, :hidden').val('');
                                $('#postform').hide();
                                $('#submitmessage').addClass('alert-box success').html('Success! We have received your request and should receive a confirmation email shortly.');
                                $('#resultsdiv').html('<p><strong>Here is a review of your request:</strong></p><p><strong>Request Date:</strong> ' + data.request_date + '</p><p><strong>Delivery Date:</strong> ' + data.request_date + '</p><p><strong>Return Date:</strong> ' + data.return_date + '</p><p><a href="/library_new/forms/avrequest.php">Submit another request</a></p>');
                            })
                            .fail(function(data,status,xhr) {
                                console.log( status );
                            })
                            .always(function(data,status,xhr) {
                                console.log( data );
                            });
                    }
                }); 
            });
            -->
        </script>

So let's say I sumbit a completely blank form. I'll end up receiving this as a response in the console:

success

{errors: Object}errors: Objectfields: Object
deliverDate: "This value should not be blank."
returnDate: "This value should not be blank."
...

And the code within the success function runs, not the error code.

Upvotes: 3

Views: 2237

Answers (1)

Ravioli87
Ravioli87

Reputation: 835

return new JsonResponse(array(
    'errors' => $this->getFormErrors($form)
), 400);

instead of

return new JsonResponse(array(
    'errors' => $this->getFormErrors($form, 400)
));

...minor detail...

Upvotes: 3

Related Questions