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:
If I can figure out what I’m doing wrong I’d like to add Regex validation to each element as well.
If you just want to remove empty elements,
delete_empty should do the trick and you could remove
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
->add('keywords', CollectionType::class, [ 'allow_add' => true, 'delete_empty' => true, 'constraints' => [ new Count(['min' => 1]), ], 'entry_options' => [ 'constraints' => [ new Regex(['pattern' => '/whateverpattern/']), ], ], ])