Forms 验证Symfony 2中的未映射字段(单选按钮)失败
其他字段已存在并映射到实体。只有1个字段未映射到带有以下代码的单选按钮。其余的田地都运转良好Forms 验证Symfony 2中的未映射字段(单选按钮)失败,forms,validation,symfony,Forms,Validation,Symfony,其他字段已存在并映射到实体。只有1个字段未映射到带有以下代码的单选按钮。其余的田地都运转良好 add->('verifyLicence','choice', array('mapped' => false, 'required' => true, 'expanded' => true, 'multiple' => false,
add->('verifyLicence','choice',
array('mapped' => false,
'required' => true,
'expanded' => true,
'multiple' => false,
'choices' => array(0=>'Yes', 1=>'No'),
'constraints' => array(
new Assert\NotNull(array('message' => 'You need to verify the licence info.')),
)));
但无论何时我提交表单,验证都不会生效。有什么问题吗
更新
这是我的控制器:
public function submitAction() {
$form = $this->createForm(new MyFormType($obj));
if ($request->isMethod('POST')) {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
// Some more codes.
} else {
$errors = $this->get('validator')->validate($hire);
}
}
return [
'hire' => $hire,
'action' => $action,
'errors' => $errors ?: [],
'form' => $form->createView(),
'calendar' => $calendar,
];
}
编辑
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults(array(
'data_class' => "Entity\Driver",
'show_operator' => false,
'code' => '',
'action' => '',
))
->addAllowedTypes([
'show_operator' => 'bool',
'code' => 'string',
'action' => 'string',
]);
}
以下是我的看法:
{{ form_widget(form.verifyLicence) }}
{{ form_errors(form.verifyLicence) }}
我建议您使用所描述的必需属性 因此,您可以添加为:
add->('verifyLicence','choice', array('mapped' => false,
'expanded' => true,
'multiple' => false,
'choices' => array(0=>'Yes', 1=>'No'),
'required' => true,
));
在这种情况下,您应该使用
Assert\False
validator
'constraints' => [
new Assert\False(['message' => 'You need to verify the licence info.']),
]));
我建议您重写表单字段,如下所示:
$builder->add(
'verifyLicence',
'choice',
[
'mapped' => false,
'required' => true,
'expanded' => true,
'multiple' => false,
'choices' => [1 => 'Yes', 0 => 'No'],
'constraints' => [
new Assert\True(['message' => 'You need to verify the licence info.']),
]
]
);
尝试简单地设置'required'=>true,而不是查找验证器。请发布控制器操作代码。您正在调用
$form->isValid()
?@sjagr我刚刚更新了我的问题。@jack我认为默认情况下是这样的。请检查您是否没有使用setDefaultOptions()
方法覆盖任何验证组。如果您使用的是验证组,则必须将其传递给约束。不管怎样,我试过了,但还是一样。