Skip to content

Instantly share code, notes, and snippets.

@bpesquet
Last active March 22, 2016 15:45
Show Gist options
  • Save bpesquet/a27232767712c72406c1 to your computer and use it in GitHub Desktop.
Save bpesquet/a27232767712c72406c1 to your computer and use it in GitHub Desktop.
Using Symfony choice form field type with Silex
// Classe RapportVisiteType
<?php
namespace GSB\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class RapportVisiteType extends AbstractType
{
private $praticiens;
/**
* Constructeur.
*
* @param array $praticiens Liste des praticiens
*/
public function __construct(array $praticiens)
{
$this->praticiens = $praticiens;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Transforme le tableau id => objet en un tableau chaîne => id pour la liste déroulante
$choices = array();
foreach ($this->praticiens as $id => $praticien) {
$cle = $praticien->__toString();
$choices[$cle] = $id;
}
$builder
->add('praticien', 'choice', array(
'label' => "Praticien",
'choices' => $choices,
'choices_as_values' => true, // Future valeur par défaut dans Symfony 3.x
'choice_value' => function ($choice) {
return $choice;
},
'expanded' => false,
'multiple' => false,
'mapped' => false // ce champ n'est pas mis en correspondance avec la propriété de l'objet
))
->add('date', 'date', array(
'label' => "Date",
'widget' => 'single_text', // Pour rendre le champ comme un input de type 'date'
))
->add('motif', 'textarea', array(
'label' => "Motif",
'attr' => array(
'rows' => '4',
)
))
->add('bilan', 'textarea', array(
'label' => "Bilan",
'attr' => array(
'rows' => '4',
)
))
->add('save', 'submit', array(
'label' => 'Ajouter',
));
}
public function getName()
{
return 'RapportVisite';
}
}
// ...
$rapportVisite = new RapportVisite();
$praticiens = $app['dao.praticien']->findAll();
$rapportVisiteForm = $app['form.factory']->create(new RapportVisiteType($praticiens), $rapportVisite);
$rapportVisiteForm->handleRequest($request);
if ($rapportVisiteForm->isSubmitted() && $rapportVisiteForm->isValid()) {
// Ajoute manuellement le praticien au nouveau rapport
$praticienId = $rapportVisiteForm->get('praticien')->getData();
$praticien = $app['dao.praticien']->find($praticienId);
$rapportVisite->setPraticien($praticien);
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment