Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 choice constraint/validation on entity field type

I have an entity field type with multiple selection :

$builder
  ->add('products', 'entity', array(
    'class' => 'Acme\MyBundle\Entity\Product',
    'choices' => $this->getAvailableProducts(),
    'multiple' => true,
  ))
;

I would like to add a min/max constraint on this field,

use Symfony\Component\Validator\Constraints\Choice;
...
'constraints' => array(new Choice(array(
    'min' => $min,
    'max' => $max,
    'multiple' => true,
    'choices' => $this->getAvailableProducts()->toArray(),
))),

But in this case, when the form is bound, the value bound for the 'products' field is a doctrine ArrayCollection, the validator throw an exception if an array is not given. "Expected argument of type array, object given"

Does it mean I have to use a 'choice' field in order to use the min/max constraint ?

like image 770
Thomas Piard Avatar asked Dec 03 '25 14:12

Thomas Piard


1 Answers

As you have multiple set to true the validator will receive a collection after binding your form.

You can validate the number of entites in the collection using the count validation constraint.

The Count validation constraint

Validates that a given collection's (i.e. an array or an object that implements Countable) element count is between some minimum and maximum value.

like image 137
Nicolai Fröhlich Avatar answered Dec 06 '25 07:12

Nicolai Fröhlich