Get all errors along with fields the error is connected to

前端 未结 7 1511
予麋鹿
予麋鹿 2021-01-03 06:43

I\'m using Symfony2 forms to validate POST and PUT requests to an API. The form handles binding the request data to the underlying entity and then validating the entity. Eve

7条回答
  •  误落风尘
    2021-01-03 07:06

    For Symfony 4.x+ (may working with lower versions).

    // $form = $this->createForm(SomeType::class);
    // $form->submit($data);
    // if (!$form->isValid()) {
    //     var_dump($this->getErrorsFromForm($form));
    // }
    
    private function getErrorsFromForm(FormInterface $form, bool $child = false): array
    {
        $errors = [];
    
        foreach ($form->getErrors() as $error) {
            if ($child) {
                $errors[] = $error->getMessage();
            } else {
                $errors[$error->getOrigin()->getName()][] = $error->getMessage();
            }
        }
    
        foreach ($form->all() as $childForm) {
            if ($childForm instanceof FormInterface) {
                if ($childErrors = $this->getErrorsFromForm($childForm, true)) {
                    $errors[$childForm->getName()] = $childErrors;
                }
            }
        }
    
        return $errors;
    }
    

提交回复
热议问题