实体字段类型的Symfony2选择约束/验证

Tho*_*ard 3 php symfony doctrine-orm

我有一个具有多个选择的实体字段类型:

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

我想在这个字段上添加一个最小/最大约束,

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

但在这种情况下,当绑定表单时,'products'字段的值绑定是一个doctrine ArrayCollection,如果没有给出数组,验证器会抛出异常."类型数组的预期参数,给定的对象"

这是否意味着我必须使用"选择"字段才能使用最小/最大约束?

Nic*_*ich 5

当你有多个设置为true时,验证器将在绑定表单后收到一个集合.

您可以使用计数验证约束验证集合中的entites .

计数验证约束

验证给定集合(即实现Countable的数组或对象)元素计数是否在某个最小值和最大值之间.