是否可以仅验证表单的当前字段..
例如,我有一个declarationForm,我在validation.yml中为3个字段提供规则:name,reference,commantary ..有时我不在我的构建器中添加注释字段。无论如何,当我验证表格时,它说评论不能为空(但没有现场评论)
答案 0 :(得分:1)
是的,但您必须从NotBlank
validation.yml
字段中移除commentary
条件,并在将FormBuilderInterface
字段包含在{{1}中时将其添加回构建器中}}:
$builder
// ... other fields using add()
->add('commentary', 'text', array(
'required' => true,
))
;
但请注意,这确实只会为required
和input
标记添加HTML5 label
属性。
感谢@Cerad的更好的解决方案是add validation groups to your validation.yml
字段:
AcmeBundle\Entity\Declaration: # change to your entity class
properties:
# ...
commentary:
- NotBlank: { groups: [commentaryReq] }
然后在需要时use the Form Builder with this validation group:
$form = $this->createFormBuilder($declaration, array(
'validation_groups' => array('commentaryReq'),
))
//->add(...)
;
或者如果您正在使用表单类:
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => array('commentaryReq'),
));
}
如果有帮助,您还可以specify groups based on submitted data或specify groups based on the button that was clicked。
答案 1 :(得分:0)