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));
});
}
Have a look at the validation component: http://symfony.com/doc/current/book/validation.html
You can write a callback constraint within the object you want to validate:
See the callback constraint page how to add this constraint to your entity (this depens if you are using annotations or yaml/xml).