Ошибка проверки формы Symfony2 при возврате HTTP-кода '200'

После отправки недопустимой формы через HTTP POST я ожидаю, что моя служба Symfony REST (с использованием FOSRestBundle) вернет код 400 Bad Request. Вместо этого он возвращает 200 OK, хотя он возвращает ошибки в формате JSON, как я хочу.

В своей сущности я использую

Symfony\Component\Validator\Constraints as Assert;

чтобы ни в одном из полей не было пустых записей. Например:

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

Вот мой метод контроллера:

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)
    ));

А вот моя HTML-форма с кодом AJAX при отправке:

       <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>

Допустим, я заполнил полностью пустую форму. В итоге я получу это как ответ в консоли:

success

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

И выполняется код в функции успеха, а не код ошибки.


person Ravioli87    schedule 11.12.2015    source источник


Ответы (1)


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

вместо того

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

... мелочь ...

person Ravioli87    schedule 11.12.2015