1

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.

1 Answer 1

3

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/']),
    ],
  ],    
])
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! I've been using Symfony since 2.8 and I didn't figure this out. Worked great, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.