Reputation: 1771
I'm working with Symfony to handle forms :
I have Color Type with fixed values :
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
Upvotes: 0
Views: 299
Reputation: 1181
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.
Upvotes: 1