Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How validate a selection of at least one element (or N elements) in Symfony 2?

My form as field users (entity type). How can i add validation in order to specificity that at least one user should be selected? Actually i'm adding an event listener but i don't know if this is a legit solution or not:

public function buildForm(\Symfony\Component\Form\FormBuilder $builder,
    array $options)
{
    $builder
        ->add('title', 'text', array(
            'label' => 'Titolo'
        ))
        ->add('content',  'textarea', array(
            'label' => 'Contenuto'
        ))
        ->add('sender_text',  'text', array(
            'label' => 'Mittente testuale',
        ))
        ->add('users', 'entity', array(
            'label'    => 'Destinatari',
            'class'    => 'DL\FidelityBundle\Entity\User',
            'property' => 'select_label',
            'multiple' => true
        ));
    ;

    // Valida il numero di utenti selezionati
    $builder->addEventListener(\Symfony\Component\Form\FormEvents::POST_BIND,
        function($event) {
            $form = $event->getForm();
            $data = $event->getData();

            if(!$data->users->isEmpty()) return;

            $msg = 'Occorre specificare almeno un utente destinatario';
            $form->get('users')->addError(new FormError($msg));
    });
}
like image 429
gremo Avatar asked Jul 03 '12 12:07

gremo


1 Answers

As of Symfony 2.1, you can use the Count constraint. If you are on 2.0, you can simply copy the constraint to your project and adapt its namespaces and its API (which was slightly changed between 2.0 and 2.1).

/**
 * @Assert\Count(min = 1, minMessage = "Occorre specificare almeno un utente destinatario") 
 */
private $users = new ArrayCollection();
like image 163
Bernhard Schussek Avatar answered Oct 12 '22 08:10

Bernhard Schussek