我想自定义symfony2表单中的错误处理。如果发生错误,输入字段应该有另一个类来显示输入值不正确。
我该怎么做?我知道我必须自定义渲染模板,但我真的不知道如何做到这一点。我必须自定义所有输入模板吗?如果输入中包含错误,我该如何检查?
如果你不想使用自定义表单,那么你可以这样做(我有Symfony 2.6和Bootstrap 3):
<div class="form-group {% if not form.YOUR_ELEMENT.vars.valid %}has-error{% endif %}">
{{ form_label(form.YOUR_ELEMENT) }}
{{ form_widget(form.YOUR_ELEMENT) }}
</div>
这是我的自定义表单主题解决方案。我复制了标准的widget_attributes
块,并在{# ADD ERROR START #}
和{# ADD ERROR END #}
之间添加了代码。您只需要将{% set errorClass = 'error' %}
中的值替换为您的错误类。
此解决方案将指定的错误类添加到所有有错误的小部件中。
{% block widget_attributes %}
{% spaceless %}
{# ADD ERROR START #}
{% if errors|length > 0 %}
{% set errorClass = 'error' %}
{% if attr.class is defined %}
{% set errorClass = errorClass ~ ' ' ~ attr.class %}
{% endif %}
{% set attr = attr|merge({'class': errorClass}) %}
{% endif %}
{# ADD ERROR END #}
id="{{ id }}" name="{{ full_name }}"
{%- if read_only %} readonly="readonly"{% endif -%}
{%- if disabled %} disabled="disabled"{% endif -%}
{%- if required %} required="required"{% endif -%}
{%- if max_length %} maxlength="{{ max_length }}"{% endif -%}
{%- if pattern %} pattern="{{ pattern }}"{% endif -%}
{%- for attrname, attrvalue in attr -%}
{{- " " -}}
{%- if attrname in ['placeholder', 'title'] -%}
{{- attrname }}="{{ attrvalue|trans({}, translation_domain) }}"
{%- elseif attrvalue is sameas(true) -%}
{{- attrname }}="{{ attrname }}"
{%- elseif attrvalue is not sameas(false) -%}
{{- attrname }}="{{ attrvalue }}"
{%- endif -%}
{%- endfor -%}
{% endspaceless %}
{% endblock widget_attributes %}
您可以使用表单主题并覆盖默认主题。示例:使用Twitter Bootstrap理念,查看MopaBootstrapBundle主题是如何准确应用的。
如前所述,使用表单主题化。您可以使用parent()
宏来避免重复代码:
{%- block widget_attributes -%}
{% if errors|length > 0 %}
{% set _class = 'has-error' %}
{% if attr.class is defined %}
{% set _class = _class ~ ' ' ~ attr.class|trim %}
{% endif %}
{% set attr = attr|merge({'class': _class}) %}
{% endif %}
{{- parent() -}}
{%- endblock widget_attributes -%}