我明白了,当表单字段不包含任何值时,您正试图显示一条消息。您可以在表单类中轻松完成此操作,如下所示:
buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('field_name', 'text', array(
'label' => 'Field label',
'required' => true,
'constraints' => array(
new NotBlank(array('message' => 'Write some stuff in here.'))
),
));
}
如果您需要在表单中注入不属于 Symfony2 框架的其他类型的约束,您可以create your own validation constraint。
如果您想在控制器中为表单添加一些选项,可以通过设置自己的选项在创建表单的方法中完成:
class YourController {
public function createForm(YourEntity $yourEntity){
$form = $this->createForm(new YourFormType(), $yourFormType, array(
'action' => $this->generateUrl('your_action_name',
array('your_custom_option_key' => 'Your custom option value')),
'method' => 'POST',
));
return $form;
}
// Rest of code omitted.
}
之后,您需要在表单类中的setDefaultOptions(OptionsResolverInterface $resolver) 方法中添加一个选项,如下所示:
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'your_custom_option_key' => '',
));
}
然后在buildForm(FormBuilderInterface $builder, array $options)方法中访问它,像这样:
buildForm(FormBuilderInterface $builder, array $options) {
$options['your_custom_option_key']; // Access content of your option
// The rest of code omitted.
}