Symfony2表单验证错误返回HTTP代码'200'

时间:2015-12-11 20:14:38

标签: forms rest symfony fosrestbundle http-response-codes

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

这是我提交的带有AJAX代码的HTML表单:

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

成功函数中的代码运行,而不是错误代码。

1 个答案:

答案 0 :(得分:3)

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

而不是

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

......小细节...