如何在表单中的RepeatedType上添加错误样式?

时间:2017-04-20 19:41:44

标签: php symfony twig

我尝试在我的表单中为我的RepeatedType生成的错误消息添加样式,因为它没有效果。

这是我控制器中的代码:

    public function signupAction(Request $request)
    {
        $user = new Users();

        $form = $this->createFormBuilder($user)
            ->add('email', EmailType::class, array(
                'required' => true,
                'label' => 'e-Mail'
            ))
            ->add('password', RepeatedType::class, array(
                'type' => PasswordType::class,
                'invalid_message' => 'passwords are not identicals',
                'options' => array('attr' => array('class' => 'password-field')),
                'required' => true,
                'first_options'  => array('label' => 'Password'),
                'second_options' => array('label' => 'Confirm password'),
            ))
            ->add('submit', SubmitType::class, array(
                'label' => 'Submit'
            ))
            ->getForm();

这里我的代码在我的枝条中查看:

{% block stylesheets %}
    <style>
        .error_msg {
            color: red;
        }
    </style>
{% endblock %}

{% block body %}
    {{ form_start(form) }}
        {{ form_label(form.email) }}
        {{ form_widget(form.email) }}
        <div class="error_msg">{{ form_errors(form.email) }}</div>

        {{ form_label(form.password) }}
        {{ form_widget(form.password) }}
        <div class="error_msg">{{ form_errors(form.password) }}</div>
{% endblock %}

因此,它适用于form.email但不适用于form.password。 如果我尝试在{{ form_errors(form.password.children['first']) }}上应用样式,则会显示错误2次(1表示没有样式,1表示样式。)

我该怎么做?

1 个答案:

答案 0 :(得分:2)

执行以下操作,错误仅显示一次(代码测试):

    {{ form_start(form) }}
    {{ form_widget(form.plainPassword.children['first']) }}
    <div style="background-color: red;">{{ form_errors(form.plainPassword.children['first']) }}</div>
    {{ form_widget(form.plainPassword.children['second']) }}
    <div style="background-color: red;">{{ form_errors(form.plainPassword.children['second']) }}</div>
    {{ form_end(form) }}