how to return json encoded form errors in symfony

前端 未结 6 2018
臣服心动
臣服心动 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:53

    By reading other people's answers I ended up improving it to my needs. I use it in Symfony 3.4.

    To be used in a controller like this:

    $formErrors = FormUtils::getErrorMessages($form);
    
    return new JsonResponse([
        'formErrors' => $formErrors,
    ]);
    

    With this code in a separate Utils class

    getName();
            $errors = [];
    
            /** @var FormError $formError */
            foreach ($form->getErrors(true, true) as $formError) {
                $name = '';
                $thisField = $formError->getOrigin()->getName();
                $origin = $formError->getOrigin();
                while ($origin = $origin->getParent()) {
                    if ($formName !== $origin->getName()) {
                        $name = $origin->getName() . '_' . $name;
                    }
                }
                $fieldName = $formName . '_' . $name . $thisField;
                /**
                 * One field can have multiple errors
                 */
                if (!in_array($fieldName, $errors)) {
                    $errors[$fieldName] = [];
                }
                $errors[$fieldName][] = $formError->getMessage();
            }
    
            return $errors;
        }
    }
    

提交回复
热议问题