2

我在我的项目中使用 Symfony 表单,代码如下:

表格

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('name', 'text', array('required' => true, 'error_bubbling' => true));
    $builder->add('email', 'email', array('required' => true, 'error_bubbling' => true));
    $builder->add('message', 'textarea', array('required' => true, 'error_bubbling' => true));
}

public function getDefaultOptions(array $options)
{
    $constraintCollection = new Collection(array(
        'name' => new NotBlank(array("message" => "Please fill out Name field")),
        'email' => array(new Email(array("message" => "Invalid Email", "checkMX" => true)),
                         new NotBlank(array("message" => "Please fill out Email field"))),
        'message' => new NotBlank(array("message" => "Please fill out Message field"))
    ));

    return array(
        "validation_constraint" => $constraintCollection,
    );
}

模板(树枝) -

<form action="{{ path('somePath') }}" method="post">
        <p>Contact Us :</p>
          {{ form_errors(form.name) }}
        <p> {{ form_label(form.name, "Your Name") }}
            {{ form_widget(form.name) }}
        </p>
          {{ form_errors(form.email) }}
        <p> {{ form_label(form.email, "Your Email") }}
            {{ form_widget(form.email) }}
        </p>
          {{ form_errors(form.message) }}
        <p> {{ form_label(form.message, "Your Message") }}
            {{ form_widget(form.message) }}
        </p>
        {{ form_rest(form) }}
    <div class="submit-button">
      <button class="button">Submit</button>
    </div>
</form>

当我尝试提交空表单时,它没有显示任何错误消息,所以我也添加了

{{ form_errors(form) }}之后<form>,正如我在这里看到的那样。
但现在它显示我在 Top 位置形成错误,而不是它们各自的字段。
我在这里做错了吗?谢谢你的时间。

4

1 回答 1

4

删除表单定义中的 'error_bubbling' => true 选项。此选项使字段上的任何错误都“传递”到表单,这就是您在 form_errors(form) 而不是 form_errors(field) 中看到错误的原因

于 2012-09-06T08:14:56.947 回答