how to return json encoded form errors in symfony

前端 未结 6 2042
臣服心动
臣服心动 2020-12-08 03:22

I want to create a webservice to which I submit a form, and in case of errors, returns a JSON encoded list that tells me which field is wrong.

currently I only get a

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 03:26

    I've finally found the solution to this problem here, it only needed a small fix to comply to latest symfony changes and it worked like a charm:

    The fix consists in replacing line 33

    if (count($child->getIterator()) > 0) {
    

    with

    if (count($child->getIterator()) > 0 && ($child instanceof \Symfony\Component\Form\Form)) {
    

    because, with the introduction in symfony of Form\Button, a type mismatch will occur in serialize function which is expecting always an instance of Form\Form.

    You can register it as a service:

    services:
    form_serializer:
        class:        Wooshii\SiteBundle\FormErrorsSerializer
    

    and then use it as the author suggest:

    $errors = $this->get('form_serializer')->serializeFormErrors($form, true, true);
    

提交回复
热议问题