I would like as for help. I have a form with dropdown list and I need to modify choices based on external input. I guess it should work well with eventListener
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) use($input){
$form = $event->getForm();
// get existin form child
// modify list of choices
}
All samples I have seen are using FormEvents only to add new field, but I need to modify existing field but I don't know how to access it.
thanks for help
While the original question is rather old, let me leave this here in case someone else comes across the need of altering a specific option of a field without having to replicate all options again:
<?php
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
// Get configuration & options of specific field
$config = $form->get('field_to_update')->getConfig();
$options = $config->getOptions();
$form->add(
// Replace original field...
'field_to_update',
$config->getType()->getName(),
// while keeping the original options...
array_replace(
$options,
[
// replacing specific ones
'required' => false,
]
)
);
});
Source: https://github.com/symfony/symfony/issues/8513#issuecomment-21868035
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With