Search code examples
phpformssymfonyevents

Symfony update form field base on a Symfony event


I'm working with Symfony to handle forms :

I have Color Type with fixed values :

enter image description here

I need to add other value to this fixed list base on form event

The idea is when i render the form, check if another color value exist and push this value to the current list

 ->add('color', ColorType::class, [
                'required' => false,
                'invalid_message' => 'La couleur est incorrecte.',
                'choice_label' => function ($value) {
                    return $value;
                },
            ])
 ->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'onCustomForm'])

I added an event to get the color value :

 public function onCustomForm(FormEvent $event)
    {

        $form = $event->getForm();
        $data = $form->getConfig()->getData();
        $color = $data->getColor();
//        dd($color);
}

i want to add the color value to the existant list values


Solution

  • I don't think you can achieve that with the Symfony ColorType as their is no option to add or restrict color.

    You have to use a ChoiceType

    public function onCustomForm(FormEvent $event)
    {
        $form = $event->getForm();
        /** @var SettingData $data */
        $data = $event->getData();
        // If the setting data is already set
        if ($data && !$data->getData()->isEmpty()) {
            $apiColors = ...// Fetch your colors from api
            $originalColors = $form->get('color')->getConfig()->getData();
             $form->add('color', ChoiceType::class, [
                'choices' => array_merge($apiColors, $originalColors),
                'expanded' => false,
                'multiple' => false
             ]);
        }
    }
    

    In fact adding an existing fields ('color') will remplace it.

    So, that's how you update it with you new data.