How to Dynamically Modify Forms Using Form Events

How to Dynamically Modify Forms Using Form Events

Often times, a form can’t be created statically. In this article, you’ll learn how to customize your form based on three common use-cases:

  1. Customizing your Form Based on the Underlying Data

    Example: you have a “Product” form and need to modify/add/remove a field based on the data on the underlying Product being edited.

  2. How to dynamically Generate Forms Based on user Data

    Example: you create a “Friend Message” form and need to build a drop-down that contains only users that are friends with the current authenticated user.

  3. Dynamic Generation for Submitted Forms

    Example: on a registration form, you have a “country” field and a “state” field which should populate dynamically based on the value in the “country” field.

If you wish to learn more about the basics behind form events, you can take a look at the Form Events documentation.

Customizing your Form Based on the Underlying Data

Before starting with dynamic form generation, remember what a bare form class looks like:

  1. // src/Form/Type/ProductType.php
  2. namespace App\Form\Type;
  3. use App\Entity\Product;
  4. use Symfony\Component\Form\AbstractType;
  5. use Symfony\Component\Form\FormBuilderInterface;
  6. use Symfony\Component\OptionsResolver\OptionsResolver;
  7. class ProductType extends AbstractType
  8. {
  9. public function buildForm(FormBuilderInterface $builder, array $options): void
  10. {
  11. $builder->add('name');
  12. $builder->add('price');
  13. }
  14. public function configureOptions(OptionsResolver $resolver): void
  15. {
  16. $resolver->setDefaults([
  17. 'data_class' => Product::class,
  18. ]);
  19. }
  20. }

Note

If this particular section of code isn’t already familiar to you, you probably need to take a step back and first review the Forms article before proceeding.

Assume for a moment that this form utilizes an imaginary “Product” class that has only two properties (“name” and “price”). The form generated from this class will look the exact same regardless if a new Product is being created or if an existing product is being edited (e.g. a product fetched from the database).

Suppose now, that you don’t want the user to be able to change the name value once the object has been created. To do this, you can rely on Symfony’s EventDispatcher component system to analyze the data on the object and modify the form based on the Product object’s data. In this article, you’ll learn how to add this level of flexibility to your forms.

Adding an Event Listener to a Form Class

So, instead of directly adding that name widget, the responsibility of creating that particular field is delegated to an event listener:

  1. // src/Form/Type/ProductType.php
  2. namespace App\Form\Type;
  3. // ...
  4. use Symfony\Component\Form\FormEvent;
  5. use Symfony\Component\Form\FormEvents;
  6. class ProductType extends AbstractType
  7. {
  8. public function buildForm(FormBuilderInterface $builder, array $options): void
  9. {
  10. $builder->add('price');
  11. $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
  12. // ... adding the name field if needed
  13. });
  14. }
  15. // ...
  16. }

The goal is to create a name field only if the underlying Product object is new (e.g. hasn’t been persisted to the database). Based on that, the event listener might look like the following:

  1. // ...
  2. public function buildForm(FormBuilderInterface $builder, array $options): void
  3. {
  4. // ...
  5. $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
  6. $product = $event->getData();
  7. $form = $event->getForm();
  8. // checks if the Product object is "new"
  9. // If no data is passed to the form, the data is "null".
  10. // This should be considered a new "Product"
  11. if (!$product || null === $product->getId()) {
  12. $form->add('name', TextType::class);
  13. }
  14. });
  15. }

Note

The FormEvents::PRE_SET_DATA line actually resolves to the string form.pre_set_data. Symfony\Component\Form\FormEvents serves an organizational purpose. It is a centralized location in which you can find all of the various form events available. You can view the full list of form events via the Symfony\Component\Form\FormEvents class.

Adding an Event Subscriber to a Form Class

For better reusability or if there is some heavy logic in your event listener, you can also move the logic for creating the name field to an event subscriber:

  1. // src/Form/EventListener/AddNameFieldSubscriber.php
  2. namespace App\Form\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Form\Extension\Core\Type\TextType;
  5. use Symfony\Component\Form\FormEvent;
  6. use Symfony\Component\Form\FormEvents;
  7. class AddNameFieldSubscriber implements EventSubscriberInterface
  8. {
  9. public static function getSubscribedEvents(): array
  10. {
  11. // Tells the dispatcher that you want to listen on the form.pre_set_data
  12. // event and that the preSetData method should be called.
  13. return [FormEvents::PRE_SET_DATA => 'preSetData'];
  14. }
  15. public function preSetData(FormEvent $event): void
  16. {
  17. $product = $event->getData();
  18. $form = $event->getForm();
  19. if (!$product || null === $product->getId()) {
  20. $form->add('name', TextType::class);
  21. }
  22. }
  23. }

Great! Now use that in your form class:

  1. // src/Form/Type/ProductType.php
  2. namespace App\Form\Type;
  3. // ...
  4. use App\Form\EventListener\AddNameFieldSubscriber;
  5. class ProductType extends AbstractType
  6. {
  7. public function buildForm(FormBuilderInterface $builder, array $options): void
  8. {
  9. $builder->add('price');
  10. $builder->addEventSubscriber(new AddNameFieldSubscriber());
  11. }
  12. // ...
  13. }

How to dynamically Generate Forms Based on user Data

Sometimes you want a form to be generated dynamically based not only on data from the form but also on something else - like some data from the current user. Suppose you have a social website where a user can only message people marked as friends on the website. In this case, a “choice list” of whom to message should only contain users that are the current user’s friends.

Creating the Form Type

Using an event listener, your form might look like this:

  1. // src/Form/Type/FriendMessageFormType.php
  2. namespace App\Form\Type;
  3. use Symfony\Component\Form\AbstractType;
  4. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  5. use Symfony\Component\Form\Extension\Core\Type\TextType;
  6. use Symfony\Component\Form\FormBuilderInterface;
  7. use Symfony\Component\Form\FormEvent;
  8. use Symfony\Component\Form\FormEvents;
  9. class FriendMessageFormType extends AbstractType
  10. {
  11. public function buildForm(FormBuilderInterface $builder, array $options): void
  12. {
  13. $builder
  14. ->add('subject', TextType::class)
  15. ->add('body', TextareaType::class)
  16. ;
  17. $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
  18. // ... add a choice list of friends of the current application user
  19. });
  20. }
  21. }

The problem is now to get the current user and create a choice field that contains only this user’s friends. This can be done injecting the Security service into the form type so you can get the current user object:

  1. use Symfony\Component\Security\Core\Security;
  2. // ...
  3. class FriendMessageFormType extends AbstractType
  4. {
  5. private $security;
  6. public function __construct(Security $security)
  7. {
  8. $this->security = $security;
  9. }
  10. // ....
  11. }

Customizing the Form Type

Now that you have all the basics in place you can use the features of the security helper to fill in the listener logic:

  1. // src/Form/Type/FriendMessageFormType.php
  2. namespace App\Form\Type;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityRepository;
  5. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  6. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  7. use Symfony\Component\Form\Extension\Core\Type\TextType;
  8. use Symfony\Component\Security\Core\Security;
  9. // ...
  10. class FriendMessageFormType extends AbstractType
  11. {
  12. private $security;
  13. public function __construct(Security $security)
  14. {
  15. $this->security = $security;
  16. }
  17. public function buildForm(FormBuilderInterface $builder, array $options): void
  18. {
  19. $builder
  20. ->add('subject', TextType::class)
  21. ->add('body', TextareaType::class)
  22. ;
  23. // grab the user, do a quick sanity check that one exists
  24. $user = $this->security->getUser();
  25. if (!$user) {
  26. throw new \LogicException(
  27. 'The FriendMessageFormType cannot be used without an authenticated user!'
  28. );
  29. }
  30. $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($user) {
  31. if (null !== $event->getData()->getFriend()) {
  32. // we don't need to add the friend field because
  33. // the message will be addressed to a fixed friend
  34. return;
  35. }
  36. $form = $event->getForm();
  37. $formOptions = [
  38. 'class' => User::class,
  39. 'choice_label' => 'fullName',
  40. 'query_builder' => function (UserRepository $userRepository) use ($user) {
  41. // call a method on your repository that returns the query builder
  42. // return $userRepository->createFriendsQueryBuilder($user);
  43. },
  44. ];
  45. // create the field, this is similar the $builder->add()
  46. // field name, field type, field options
  47. $form->add('friend', EntityType::class, $formOptions);
  48. });
  49. }
  50. // ...
  51. }

Note

You might wonder, now that you have access to the User object, why not just use it directly in buildForm() and omit the event listener? This is because doing so in the buildForm() method would result in the whole form type being modified and not just this one form instance. This may not usually be a problem, but technically a single form type could be used on a single request to create many forms or fields.

Using the Form

If you’re using the default services.yaml configuration, your form is ready to be used thanks to autowire and autoconfigure. Otherwise, register the form class as a service and tag it with the form.type tag.

In a controller, create the form like normal:

  1. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. class FriendMessageController extends AbstractController
  5. {
  6. public function new(Request $request): Response
  7. {
  8. $form = $this->createForm(FriendMessageFormType::class);
  9. // ...
  10. }
  11. }

You can also embed the form type into another form:

  1. // inside some other "form type" class
  2. public function buildForm(FormBuilderInterface $builder, array $options): void
  3. {
  4. $builder->add('message', FriendMessageFormType::class);
  5. }

Dynamic Generation for Submitted Forms

Another case that can appear is that you want to customize the form specific to the data that was submitted by the user. For example, imagine you have a registration form for sports gatherings. Some events will allow you to specify your preferred position on the field. This would be a choice field for example. However, the possible choices will depend on each sport. Football will have attack, defense, goalkeeper etc… Baseball will have a pitcher but will not have a goalkeeper. You will need the correct options in order for validation to pass.

The meetup is passed as an entity field to the form. So we can access each sport like this:

  1. // src/Form/Type/SportMeetupType.php
  2. namespace App\Form\Type;
  3. use App\Entity\Position;
  4. use App\Entity\Sport;
  5. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  6. use Symfony\Component\Form\AbstractType;
  7. use Symfony\Component\Form\FormBuilderInterface;
  8. use Symfony\Component\Form\FormEvent;
  9. use Symfony\Component\Form\FormEvents;
  10. // ...
  11. class SportMeetupType extends AbstractType
  12. {
  13. public function buildForm(FormBuilderInterface $builder, array $options): void
  14. {
  15. $builder
  16. ->add('sport', EntityType::class, [
  17. 'class' => Sport::class,
  18. 'placeholder' => '',
  19. ])
  20. ;
  21. $builder->addEventListener(
  22. FormEvents::PRE_SET_DATA,
  23. function (FormEvent $event) {
  24. $form = $event->getForm();
  25. // this would be your entity, i.e. SportMeetup
  26. $data = $event->getData();
  27. $sport = $data->getSport();
  28. $positions = null === $sport ? [] : $sport->getAvailablePositions();
  29. $form->add('position', EntityType::class, [
  30. 'class' => Position::class,
  31. 'placeholder' => '',
  32. 'choices' => $positions,
  33. ]);
  34. }
  35. );
  36. }
  37. // ...
  38. }

When you’re building this form to display to the user for the first time, then this example works perfectly.

However, things get more difficult when you handle the form submission. This is because the PRE_SET_DATA event tells us the data that you’re starting with (e.g. an empty SportMeetup object), not the submitted data.

On a form, we can usually listen to the following events:

  • PRE_SET_DATA
  • POST_SET_DATA
  • PRE_SUBMIT
  • SUBMIT
  • POST_SUBMIT

The key is to add a POST_SUBMIT listener to the field that your new field depends on. If you add a POST_SUBMIT listener to a form child (e.g. sport), and add new children to the parent form, the Form component will detect the new field automatically and map it to the submitted client data.

The type would now look like:

  1. // src/Form/Type/SportMeetupType.php
  2. namespace App\Form\Type;
  3. use App\Entity\Position;
  4. use App\Entity\Sport;
  5. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  6. use Symfony\Component\Form\FormInterface;
  7. // ...
  8. class SportMeetupType extends AbstractType
  9. {
  10. public function buildForm(FormBuilderInterface $builder, array $options): void
  11. {
  12. $builder
  13. ->add('sport', EntityType::class, [
  14. 'class' => Sport::class,
  15. 'placeholder' => '',
  16. ])
  17. ;
  18. $formModifier = function (FormInterface $form, Sport $sport = null) {
  19. $positions = null === $sport ? [] : $sport->getAvailablePositions();
  20. $form->add('position', EntityType::class, [
  21. 'class' => Position::class,
  22. 'placeholder' => '',
  23. 'choices' => $positions,
  24. ]);
  25. };
  26. $builder->addEventListener(
  27. FormEvents::PRE_SET_DATA,
  28. function (FormEvent $event) use ($formModifier) {
  29. // this would be your entity, i.e. SportMeetup
  30. $data = $event->getData();
  31. $formModifier($event->getForm(), $data->getSport());
  32. }
  33. );
  34. $builder->get('sport')->addEventListener(
  35. FormEvents::POST_SUBMIT,
  36. function (FormEvent $event) use ($formModifier) {
  37. // It's important here to fetch $event->getForm()->getData(), as
  38. // $event->getData() will get you the client data (that is, the ID)
  39. $sport = $event->getForm()->getData();
  40. // since we've added the listener to the child, we'll have to pass on
  41. // the parent to the callback functions!
  42. $formModifier($event->getForm()->getParent(), $sport);
  43. }
  44. );
  45. }
  46. // ...
  47. }

You can see that you need to listen on these two events and have different callbacks only because in two different scenarios, the data that you can use is available in different events. Other than that, the listeners always perform exactly the same things on a given form.

Tip

The FormEvents::POST_SUBMIT event does not allow to modify the form the listener is bound to, but it allows to modify its parent.

One piece that is still missing is the client-side updating of your form after the sport is selected. This should be handled by making an AJAX call back to your application. Assume that you have a sport meetup creation controller:

  1. // src/Controller/MeetupController.php
  2. namespace App\Controller;
  3. use App\Entity\SportMeetup;
  4. use App\Form\Type\SportMeetupType;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. // ...
  9. class MeetupController extends AbstractController
  10. {
  11. public function create(Request $request): Response
  12. {
  13. $meetup = new SportMeetup();
  14. $form = $this->createForm(SportMeetupType::class, $meetup);
  15. $form->handleRequest($request);
  16. if ($form->isSubmitted() && $form->isValid()) {
  17. // ... save the meetup, redirect etc.
  18. }
  19. return $this->render(
  20. 'meetup/create.html.twig',
  21. ['form' => $form->createView()]
  22. );
  23. }
  24. // ...
  25. }

The associated template uses some JavaScript to update the position form field according to the current selection in the sport field:

  1. {# templates/meetup/create.html.twig #}
  2. {{ form_start(form) }}
  3. {{ form_row(form.sport) }} {# <select id="meetup_sport" ... #}
  4. {{ form_row(form.position) }} {# <select id="meetup_position" ... #}
  5. {# ... #}
  6. {{ form_end(form) }}
  7. <script>
  8. var $sport = $('#meetup_sport');
  9. // When sport gets selected ...
  10. $sport.change(function() {
  11. // ... retrieve the corresponding form.
  12. var $form = $(this).closest('form');
  13. // Simulate form data, but only include the selected sport value.
  14. var data = {};
  15. data[$sport.attr('name')] = $sport.val();
  16. // Submit data via AJAX to the form's action path.
  17. $.ajax({
  18. url : $form.attr('action'),
  19. type: $form.attr('method'),
  20. data : data,
  21. success: function(html) {
  22. // Replace current position field ...
  23. $('#meetup_position').replaceWith(
  24. // ... with the returned one from the AJAX response.
  25. $(html).find('#meetup_position')
  26. );
  27. // Position field now displays the appropriate positions.
  28. }
  29. });
  30. });
  31. </script>

The major benefit of submitting the whole form to just extract the updated position field is that no additional server-side code is needed; all the code from above to generate the submitted form can be reused.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.