【发布时间】:2014-10-16 07:50:49
【问题描述】:
我想将我的表单错误输出到 screent,但我不能这样做。
{{ form_errors(form) }} - in my view file is not working for me.
如果表单无效,我可能需要使用 $form->getErrors()。然后将其传递给模板? 我试图寻找答案,但我没有得到任何结果。请帮帮我。
我的操作(联系表单),我尝试返回带有错误的渲染页面:
public function contactAction(Request $request)
{
$form = $this->createForm(new ContactType());
$formView = $form->createView();
$form->handleRequest($request);
if ($form->isValid()) {
....
} else {
$errors = $form->getErrors();
return $this->render('VputiMainBundle:Main:contact.html.twig', array('form' => $formView, 'errors' => $errors));
}
return $this->render('VputiMainBundle:Main:contact.html.twig', array('form' => $formView));
}
联系人类型:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text', array(
'label' => 'Ваше имя',
'attr' => array(
'placeholder' => 'Ваше имя',
'class' => 'form-control',
'name' => 'InputName',
'id' => "InputName"
),
));
$builder->add('email', 'email', array(
'label' => 'Ваш e-mail',
'attr' => array(
'placeholder' => 'Ваш e-mail',
'class' => "form-control",
'id' => "InputEmail",
'name' => "InputEmail",
),
));
$builder->add('subject', 'text', array(
'label' => 'Тема вопроса',
'attr' => array(
'placeholder' => 'Тема вопроса',
'class' => "form-control",
'id' => "InputSubject",
'name' => "InputSubject",
),
));
$builder->add('body', 'textarea', array(
'label' => 'Вопрос',
'attr' => array(
'placeholder' => 'Вопрос',
'name' => "InputMessage",
'id' => "InputMessage",
'class' => "form-control",
'rows' => "5",
),
));
$builder->add('recaptcha', 'ewz_recaptcha', array(
'label' => 'Код с картинки',
'attr' => array(
'options' => array(
'theme' => 'clean',
)
),
'mapped' => false,
'constraints' => array(
new True(),
)
));
$builder->add('submit', 'submit', array(
'label' => 'Спросить',
'attr' => array(
'name' => "submit",
'id' => "submit",
'value' => "Submit",
'class' => "btn btn-info pull-right",
),
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$constraints = new Collection(array(
'name' => array(
new NotBlank(array('message' => 'Name should not be blank.')),
new Length(array('min' => 2)),
),
'email' => array(
new NotBlank(array('message' => 'Email should not be blank.')),
new Email(array('message' => 'Invalid email address.')),
),
'subject' => array(
new NotBlank(array('message' => 'Subject should not be blank.')),
new Length(array('min' => 3)),
),
'body' => array(
new NotBlank(array('message' => 'Message should not be blank.')),
new Length(array('min' => 5)),
),
));
$resolver->setDefaults(array(
'constraints' => $constraints,
));
}
public function getName()
{
return 'contact_form';
}
【问题讨论】:
-
您是否从控制器操作中传递了
form? -
是的,如果有帮助,我可以将我的控制器添加到问题中
-
是的,请添加控制器动作代码。
-
form_errors(form)用于不特定于任何字段的全局错误。你可以在任何领域尝试form_errors吗?即form_errors(form.name) -
没有结果...页面刚刚重新加载...
标签: forms validation symfony