简体   繁体   English

Symfony表单错误呈现

[英]Symfony Form Error Rendering

I have the following Problem. 我有以下问题。 I use Symfony Forms to Validate a JSON Request, that also works great. 我使用Symfony表单来验证JSON请求,这也很好用。 But i will also the thrown Errors in a more Json readable way. 但是我也将以更易读的Json方式抛出错误。

Is it possible that i can get from the FormErrorIterator FormError for each Error the relevant Field name. 是否有可能我可以从FormErrorIterator FormError获取每个错误的相关字段名称。

For Example: 例如:

formName.SubForm.Propertyname => 'MyErrorMessage'

the structure of the path could be also an Array. 路径的结构也可以是数组。

If you want to retrieve the errors of your form in an array you could add and use this method in your controller : 如果要检索数组中表单的错误,可以在控制器中添加并使用此方法:

private function getErrorMessages(\Symfony\Component\Form\Form $form) {
    $errors = array();

    foreach ($form->getErrors() as $key => $error) {
        if ($form->isRoot()) {
            $errors['#'][] = $error->getMessage();
        } else {
            $errors[] = $error->getMessage();
        }
    }

    foreach ($form->all() as $child) {
        if (!$child->isValid()) {
            $errors[$child->getName()] = $this->getErrorMessages($child);
        }
    }

    return $errors;
}

$errors will contain an array of errors and if a field has an error the field name will be used as a key in the array : $ errors将包含一个错误数组,如果一个字段有错误,则该字段名称将用作该数组中的键:

$errors['FIELD_NAME'] = ERROR_MSG. $ errors ['FIELD_NAME'] = ERROR_MSG。

Depending of your Symfony version you might need or want other versions of this method : Symfony2 : How to get form validation errors after binding the request to the form . 根据您的Symfony版本,您可能需要或需要此方法的其他版本: Symfony2:在将请求绑定到表单后如何获取表单验证错误

UPDATE UPDATE

If your validation constraints are on a field of the Entity class, they will be in the errors array with a key based on the field name. 如果您的验证约束位于Entity类的某个字段上,则它们将位于errors数组中,并且具有基于字段名称的键。

If your validation constraints are on the Entity class, the will be in the # key or numeric key depending if the form is root or not. 如果验证约束位于Entity类上,则将在#键或数字键中,具体取决于表单是否为root。

Entity class example 实体类示例

/**
 * @Assert\Callback("isValidName") <- this error will be in $errors['#']
 */
class Author
{
    /**
     * @Assert\NotBlank() <- this error will be in $errors['firstname']
     */
    public $firstname;
}

If you want only errors on field, you need to move all your Entity class asserts on the Entity fields. 如果只想在字段上输入错误,则需要在Entity字段上移动所有Entity类的断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM