0
votes

I'm trying to pass associative array as options for a ChoiceType field in my OrdreMissionType form :

$typeJour = ['Travaillée(s)' => "T", 'Calendaire(s)' => "C"];
$form = $this->createForm(OrdreMissionType::class, $odm,[
        'user' => $user,
        'affairesOdm' => $affairesForm,
        'typeJour' => $typeJour,
        'method' => 'PUT'
    ]);

$form->handleRequest($request);

if($form->isSubmitted() && $form->isValid()) {
        $odm = $form->getData();
        dd($odm);

        $em = $this->getDoctrine()->getManager();
        $em->persist($odm);
        $em->flush();
 }

My FormType class :

class OrdreMissionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
         //...
         $typeJour = $options['typeJour'];
         $builder->add('typeJour', ChoiceType::class, [
            'label' => 'Type de(s) journée(s)',
            'placeholder' => 'Sélectionnez une option',
            'choices' => $typeJour,
            'label_attr' => ['class' => 'radio-inline'],
         ]);
        //...
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'typeJour' => false,
            'data_class' => OrdreMission::class
        ]);
    }
}

My Entity :

class OrdreMission
{
    //...
    /**
    * @ORM\Column(type="string", length=255)
    */
    private $typeJour;
    //...
}

My problem is, when I submit the form, the 'typeForm' field is always null, here's the output of the 'dd' line :

enter image description here

I don't want to put the choices in a specific table on my database, because they will never change. Does somebody knows how to fix this problem ? Any help would be grateful. Thank you in advance !

2

2 Answers

0
votes

You need to add optinon 'empty_data' into field properties of your form.

    public function buildForm(FormBuilderInterface $builder, array $options)
{
     //...
     $typeJour = $options['typeJour'];
     $builder->add('typeJour', ChoiceType::class, [
        'empty_data' => 'T', //OR C
        'label' => 'Type de(s) journée(s)',
        'placeholder' => 'Sélectionnez une option',
        'choices' => $typeJour,
        'label_attr' => ['class' => 'radio-inline'],
     ]);
    //...
}

FYI: method configureOptions() is not for confugure particular fields, it is form configuration. Also, you can't assign default value not from scope(T or C in your case)

0
votes

I found a workaround for this problem, I added the option "expanded => true" and my field takes now the value selected. I do not have the same graphic rendering, but at least, it's working !

$builder->add('typeJour', ChoiceType::class, [
        'label' => 'Type de(s) journée(s)',
        'placeholder' => 'Sélectionnez une option',
        'expanded' => true,
        'choices' => ['Travaillée(s)' => "T", 'Calendaire(s)' => "C"]
    ]);