'How to use form events to dynamically modify fields when i choice a specific value

I have some problems in my forum's project.

I have one field named "Category" with choice list and i want to when i check the value "Characters" in this list, a new field with entity "subCategory" appear to display a list of these characters.

This field must be added only if the value "Characters" is selected.

I tried something like :

->add('category', EntityType::class, [
            'class' => Category::class,          
            'choice_label' => 'title',
            ])
        ->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
        $sub = $event->getData();
        $form = $event->getForm();

        if (isset($sub['title']) && $sub['title'] == 'Personnages') {
        $form->add('subCategory', EntityType::class, [
        'class' => SubCategory::class,
        'choice_label' => 'name']);
        }
            
 })        
        ->add('subCategory', EntityType::class, [
        'class' => SubCategory::class,
        'choice_label' => 'name',
        ])
    

That means "If isset a title in Category and her value is Characters, add a field which add list of these characters"

I know that i have to use form events but i don't know the way to resolve it.

Thanks for support



Solution 1:[1]

I'm afraid you can't do this with Form Events. I hope I don't say you bullsh*t but it seems the event types proposed by this feature are not designed for "real-time" modification of the form. As stated by the documentation:

  1. Pre-populating the Form (FormEvents::PRE_SET_DATA and FormEvents::POST_SET_DATA)
  2. Submitting a Form (FormEvents::PRE_SUBMIT, FormEvents::SUBMIT and FormEvents::POST_SUBMIT)

Nothing about dynamic detection of field values.

My best suggestion here would be to do with another way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryierth