Symfony 4 CollectionType Constraints – array of strings

Tags: , , , ,



I have a very simple array of strings being stored in a database and provided via an API.

Using Symfony’s form types I’m adding validation for various bits of data.

I’ve hit a wall with a CollectionType that is essentially an array of strings, for example:

['key', 'words', 'are', 'the', 'best']

With the form code:

->add('keywords', CollectionType::class, [
    'allow_add' => true,
    'constraints' => [
        new Count(['min' => 1]),
        new NotBlank(['allowNull' => false])
    ]
])

This is allowing the following to pass the constraints:

[null] and ['']

If I can figure out what I’m doing wrong I’d like to add Regex validation to each element as well.

Answer

If you just want to remove empty elements, delete_empty should do the trick and you could remove NotBlank.

To apply additional validation to the elements, you’ll have to pass the constraint to the collection item, not to the collection itself, by using entry_options:

->add('keywords', CollectionType::class, [
  'allow_add' => true,
  'delete_empty' => true,
  'constraints' => [
    new Count(['min' => 1]),
  ],
  'entry_options' => [
    'constraints' => [
      new Regex(['pattern' => '/whateverpattern/']),
    ],
  ],    
])


Source: stackoverflow