Validate checkbox not mapped to entity in a symfony2 form

I add a non mapped field to a symfony2 form type:

$builder->add('terms','checkbox', array('mapped' => false,
        'constraints' => array(new NotBlank())));

But the NotBlank() constraint is not working! Only if I change the type from 'checkbox' to 'text' it is working as expected. So how can I validate a checkbox? Of course I tried with 'True()', 'EqualTo()' and 'Length(...)' constraints too. But without success. I also tried different POST values (1/0, true/false, on/off...) for the field.

What is the big difference between a checkbox field and a text field regarding form field validation in symfony2?

Thanx Stef


NotBlank validates string to be not empty. Try to use NotNull

True must also works.

Validates that a value is true. Specifically, this checks to see if the value is exactly true, exactly the integer 1, or exactly the string "1". This constraint can be applied to properties (eg a termsAccepted property on a registration model).


Symfony 3.0的更新回答

use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentValidatorConstraintsIsTrue;

// ...
{
    $builder->add('terms', CheckboxType::class, array('constraints'=>new IsTrue(array('message'=>'Needs to be clicked')));
}
链接地址: http://www.djcxy.com/p/57890.html

上一篇: Symfony 2.5中ValidatorConstraint的问题

下一篇: 验证复选框未以symfony2格式映射到实体