Symfony 2.0: How to validate inline collection of forms without entity

How can I validate a built-in collection of forms (no entities) in Symfony 2.0? Upgrading to 2.1 is not a convenient option at the moment if the solution lies along this line.

I tried using constraint Valid

and it resulted in all validation failing.

public function getDefaultOptions(array $options)
{
    $collectionConstraint = new Collection(array (
        ...

        // I tried Valid constraint but this "removes" all validation
        'travel_links' => new Valid(),
    ));

    return array ('validation_constraint' => $collectionConstraint);
}

      

+3


source to share


2 answers


In Symfony 2.1, you can use the option :

$builder
->add('firstName', 'text', array(
   'constraints' => new Length(array('min' => 3)),
))
->add('lastName', 'text', array(
   'constraints' => array(
       new NotBlank(),
       new Length(array('min' => 3)),
),
));

      

Obviously doesn't work in Symfony 2.0; however, in Symfony 2.0 there is a limited validation_constraint constraint parameter .



$builder
->add('firstName', 'text', array(
   'validation_constraint' => new Length(array('min' => 3)),
));

      

If you need to check multiple conditions (e.g. NotBlank, Lenght), you can help yourself by specifying a Custom Limit that performs the entire check at once. :)

Edit: Don't forget to enable use Symfony\Component\Validator\Constraints\Length

or whatever constraint you are using. :)

+3


source


In real version of Symfony2.x you can set cascade_validation to true (default is false) http://symfony.com/doc/current/reference/forms/types/form.html

The documentation says: "Set this parameter to true to force validation on built-in form types. For example, if you have a ProductType with a built-in CategoryType, setting cascade_validation to true on ProductType will cause the data from the TypeType to be validated as well.



Instead of using this option, you can also use the Valid constraint in your model to force validation of the child object stored in the property. "

+1


source







All Articles