Get all errors along with fields the error is connected to

前端 未结 7 1478
予麋鹿
予麋鹿 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:26

    Use this function to get all error messages after binding form.

    private function getErrorMessages(\Symfony\Component\Form\Form $form) {
        $errors = array();
        foreach ($form->getErrors() as $key => $error) {
            $template = $error->getMessageTemplate();
            $parameters = $error->getMessageParameters();
    
            foreach($parameters as $var => $value){
                $template = str_replace($var, $value, $template);
            }
    
            $errors[$key] = $template;
        }
        if ($form->hasChildren()) {
            foreach ($form->getChildren() as $child) {
                if (!$child->isValid()) {
                    $errors[$child->getName()] = $this->getErrorMessages($child);
                }
            }
        }
        return $errors;
    }
    

提交回复
热议问题