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));
});
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With