简体   繁体   English

文件上载中的错误消息自定义

[英]Error message customization in file upload

Using the guide http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html i'm trying to customize error message, but i've a problem: variable errors is not defined, as we don't validate an entity and we are not calling $this->get('validator')->validate($entity) . 使用指南http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html我正在尝试自定义错误消息,但我遇到了一个问题:未定义变量errors ,因为我们不验证一个实体,我们不是在调用$this->get('validator')->validate($entity)

{% block field_errors %}
{% spaceless %}
    {# errors is undefined here #}
{% endspaceless %}
{% endblock field_errors %}

This is the sample code: 这是示例代码:

public function uploadAction()
{
    $document = new Document();
    $form = $this->createFormBuilder($document)
        ->add('name')
        ->add('file')
        ->getForm()
    ;

    if ($this->getRequest()->getMethod() === 'POST') {
        $form->bindRequest($this->getRequest());
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();

            $em->persist($document);
            $em->flush();

            $this->redirect($this->generateUrl('...'));
        }
    }

    // Variable 'errors' is not assigned
    return array('form' => $form->createView());
}

Not sure I understand. 不确定我理解。 If you are following the example then $document has validation rules on it which will be tested by $form->isValid(). 如果您正在关注该示例,那么$ document上有验证规则,将由$ form-> isValid()进行测试。 {{ form_errors(form) }} should output any errors. {{form_errors(form)}}应该输出任何错误。

If it is just a template customization question then you need to test for the existence of errors before trying to process them: 如果它只是一个模板自定义问题,那么您需要在尝试处理错误之前测试是否存在错误:

{% block field_errors %}
{% spaceless %}
    {% if errors|length > 0 %}
    <span style="color:red">
        {% for error in errors %}
            {{ error.messageTemplate|trans(error.messageParameters, 'validators') }}<br />
        {% endfor %}
    {% endif %}
{% endspaceless %}
{% endblock field_errors %}

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

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