vendredi 27 février 2015

Allow all value on choice field type in Symfony2 form builder

I have a problem for a while and i have read a lot of topic with similar problem but cant implement the answer in my case.


I have a select field that i populate with Ajax. so in my form builder i have this code :



VilleType.php




/**
* @ORM\Entity(repositoryClass="MDB\AnnonceBundle\Entity\RegisterRepository")
*/
class VilleType extends AbstractType {

/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('nomComplet', 'choice'
);
}

/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MDB\AdresseBundle\Entity\Ville'
));
}

/**
* @return string
*/
public function getName() {
return 'mdb_adressebundle_ville';
}
}


But my form is never valid because their is no value in this choice field. But i cant add the value inside cause i cant know in advance what the user will put as value.


So my question is how to disable verification on this field from symfony. Or let it allow all value.


Thanks



EDIT



Here, i tried a new approch. I use The event listner to modify my field with the value than the user submitted.



public function buildForm(FormBuilderInterface $builder, array $options) {

$builder
->add('nomComplet', 'choice');


$builder->get('nomComplet')->addEventListener(
FormEvents::PRE_SUBMIT, function(FormEvent $event) /* use ($formModifier) */ {

$ville = $event->getData();
$event->getForm()->add('nomComplet', 'choice', array('choices' => $ville));
// $formModifier($event->getForm()->getParent(), $ville);
}
);
}

/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'MDB\AdresseBundle\Entity\Ville'
));
}

/**
* @return string
*/
public function getName() {
return 'mdb_adressebundle_ville';
}

}


But it still not working, i have the following error :



You cannot add children to a simple form. Maybe you should set the option "compound" to true?



So if someone know how to use this way with eventListener it would be great.


Thx


Aucun commentaire:

Enregistrer un commentaire