This example is about changing the form depending on decisions the user did with the form previously.
In my special case, I needed to disable a selectbox, if a certain checkbox wasn't set.
So we have the FormBuilder, where we'll set the EventListener
on the FormEvents::PRE_SUBMIT
event. We're using this event, because the form is already set with the submitted data of the form, but we're still able to manipulate the form.
class ExampleFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$data = $builder->getData();
$builder
->add('choiceField', ChoiceType::class, array(
'choices' => array(
'A' => '1',
'B' => '2'
),
'choices_as_values' => true,
))
->add('hiddenField', HiddenType::class, array(
'required' => false,
'label' => ''
))
->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
// get the form from the event
$form = $event->getForm();
// get the form element and its options
$config = $form->get('choiceField')->getConfig();
$options = $config->getOptions();
// get the form data, that got submitted by the user with this request / event
$data = $event->getData();
// overwrite the choice field with the options, you want to set
// in this case, we'll disable the field, if the hidden field isn't set
$form->add(
'choiceField',
$config->getType()->getName(),
array_replace(
$options, array(
'disabled' => ($data['hiddenField'] == 0 ? true : false)
)
)
);
})
;
}
}