Symfony 2:仅验证已定义字段的表单 [英] Symfony 2 : Validate form for defined fields only
问题描述
是否可以仅验证表单的当前字段.
Is it possible to validate only present fields of the form..
例如,我有一个clarificationForm,我在validation.yml中给出了3个字段的规则:名称,引用,强制..有时我没有在构建器中添加注释字段.无论如何,当我验证表单时,它说注释不能为空(但没有字段注释)
For example, I have a declarationForm, I give rules in the validation.yml for 3 fields : name, reference, commantary.. sometime I dont add commentary field in my builder. Anyway when I validate the form it says that commentary cannot be empty (but there is no field commentary)
推荐答案
是的,但是您必须从validation.yml
中删除commentary
字段的NotBlank
条件,并在任何时候将需求重新添加到构建器中您将其包含在您的FormBuilderInterface
中:
Yes, but you will have to remove the NotBlank
conditions from your validation.yml
for the commentary
field and add the requirement back into the builder whenever you include it in your FormBuilderInterface
:
$builder
// ... other fields using add()
->add('commentary', 'text', array(
'required' => true,
))
;
但是请注意,这确实只会向input
和label
标签添加HTML5 required
属性.
Note however that this does indeed only add an HTML5 required
attribute to both the input
and label
tags.
由于@Cerad,更好的解决方案是将验证组添加到您的validation.yml
字段:
The better solution thanks to @Cerad is to add validation groups to your validation.yml
for the field:
AcmeBundle\Entity\Declaration: # change to your entity class
properties:
# ...
commentary:
- NotBlank: { groups: [commentaryReq] }
然后将表单生成器与此验证组配合使用必要时:
$form = $this->createFormBuilder($declaration, array(
'validation_groups' => array('commentaryReq'),
))
//->add(...)
;
或者如果您正在使用表单类:
or if you're using Form Classes:
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => array('commentaryReq'),
));
}
您还可以指定基于关于提交的数据或指定根据点击的按钮进行分组(如果有帮助的话).
You can also specify groups based on submitted data or specify groups based on the button that was clicked if that helps.
这篇关于Symfony 2:仅验证已定义字段的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!