Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using symfony2's form type "collection", how can I validate that at least one form has been submitted?

I used this tutorial to embed a collection of forms. How can I add validation that will ensure that the form is submitted with at least one form?

like image 535
mattalxndr Avatar asked Feb 21 '23 12:02

mattalxndr


1 Answers

Symfony now has a Count constraint that can be used with collection types to set a minimum number of items:

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

$formBuilder->add('example', CollectionType::class, [
  // other options...
  'constraints' => [
    new Assert\Count([
      'min' => 1,
      'minMessage' => 'Must have at least one value',
      // also has max and maxMessage just like the Length constraint
    ]),
  ],
]);
like image 157
chrisguitarguy Avatar answered Apr 12 '23 23:04

chrisguitarguy