Forms 将错误绑定到symfony2'中的嵌入表单字段;s控制器
使用Symfony2.3.4 正如标题所解释的,我需要将错误消息绑定到嵌入的表单字段,最好是在控制器中。我的想法可能与我使用单一表单的方式类似:Forms 将错误绑定到symfony2'中的嵌入表单字段;s控制器,forms,symfony,error-handling,Forms,Symfony,Error Handling,使用Symfony2.3.4 正如标题所解释的,我需要将错误消息绑定到嵌入的表单字段,最好是在控制器中。我的想法可能与我使用单一表单的方式类似: use Symfony\Component\Form\FormError; //.... public function createAction(){ //..... $postData = current($request->request->all()); if ($postData['field_name'] == '') {
use Symfony\Component\Form\FormError;
//....
public function createAction(){
//.....
$postData = current($request->request->all());
if ($postData['field_name'] == '') {
$error = new FormError("Write some stuff in here");
$form->get('field_name')->addError($error);
}
//.....
}
或者也许应该换一种方式我需要帮助
谢谢$我明白了,您试图在表单字段不包含任何值时显示消息。您可以在表单类中轻松完成此操作,如下所示:
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.'))
),
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'your_custom_option_key' => '',
));
}
buildForm(FormBuilderInterface $builder, array $options) {
$options['your_custom_option_key']; // Access content of your option
// The rest of code omitted.
}
如果需要向表单中注入其他类型的约束,而该约束不是Symfony2框架的一部分,则可以
如果要在controller中向窗体添加一些选项,可以通过设置自己的选项来创建窗体的方法来完成:
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)
方法中添加一个选项,如下所示:
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.'))
),
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'your_custom_option_key' => '',
));
}
buildForm(FormBuilderInterface $builder, array $options) {
$options['your_custom_option_key']; // Access content of your option
// The rest of code omitted.
}
然后在buildForm(FormBuilderInterface$builder,array$options)
方法中访问它,如下所示:
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.'))
),
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver){
$resolver->setDefaults(array(
'your_custom_option_key' => '',
));
}
buildForm(FormBuilderInterface $builder, array $options) {
$options['your_custom_option_key']; // Access content of your option
// The rest of code omitted.
}