验证Symfony 2中的非映射字段(单选按钮)失败

时间:2015-05-04 17:00:09

标签: forms validation symfony

其他字段已存在并已映射到实体。只有1个字段未映射到带有下面代码的单选按钮。所有其他领域都工作正常。

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) }}

2 个答案:

答案 0 :(得分:1)

在这种情况下,您应该使用Assert\False验证程序。

'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.']),
        ]
    ]
);

答案 1 :(得分:0)

我建议您使用here所述的必需属性。

所以你可以添加为:

<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1></h1><p>Welcome to </p></body></html>