我正在使用带有silex的Symfony2表单。
我创建了这样的表单:
$form = $app->form()
->add('foo', new FooType())
// ->add(...)
->add('save', 'submit')
->getForm();
FooType:
<?php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
class FooType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('bar', 'text', ['constraints' => new Assert\NotBlank()]);
$builder->add('baz', 'text', ['required' => false]);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'error_bubbling' => false,
]);
}
public function getName()
{
return 'foo';
}
}
如果“bar”字段为空,则错误始终映射到“foo”基本字段。为什么?如何将错误映射到字段本身(“bar”)?
编辑:
表单呈现方式如下(Twig):
{{ form(form) }}
提交空字段后的结果:
<form name="form" method="post" action="">
<div>
<label class="required">Foo</label>
<ul>
<li>This value should not be blank.</li>
</ul>
<div id="form_foo">
<div>
<label for="form_foo_bar" class="required">Bar</label>
<input type="text" id="form_foo_bar" name="form[foo][bar]" required="required">
</div>
<div>
<label for="form_foo_baz">Baz</label>
<input type="text" id="form_foo_baz" name="form[foo][baz]">
</div>
</div>
</div>
<div>
<button type="submit" id="form_save" name="form[save]">Save</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="faebf2a0b0a05ddb8e5f40d58c7a3bf3d49522d4">
</form>