在我的(symfony 3.4)表单中,我想根据是否选中了同一表单中的复选框来验证字段。我尝试使用验证组,但从未验证该字段。
这是我正在使用的表单类型:
class DummyType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('createAccount', CheckboxType::class)
->add('password', PasswordType::class, [
'constraints' => [new NotBlank()],
'validation_groups' => ['password']
])
->add('submit', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'validation_groups' => function (FormInterface $form) {
$data = $form->getData();
if ($data['createAccount'] === true) {
return ['Default', 'password'];
}
return ['Default'];
}
]);
}
}
这是创建表单的动作:
/**
* @Route("/debug/form")
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function formAction(Request $request)
{
$form = $this->createForm(DummyType::class, null, ['action' => '/debug/form']);
$form->handleRequest($request);
$message = '';
if ($form->isSubmitted() && $form->isValid()) {
$message = 'Form submitted successfully';
}
return $this->render('@App/Debug/debug.html.twig', ['form' => $form->createView(), 'message' => $message]);
}
选中该复选框不会更改任何内容。该表格将始终有效。我假设指定这样的验证组会从默认组中删除password
字段(情况似乎是这样,因为对该字段的验证已完全消失)并仅添加 进入password
组。是不是这样?如果选中了该复选框,还有其他方法可以验证password
字段吗?