A panoramic, light blue background with abstract shapes and the Symfony logo, depicting a sleek and modern environment for Symfony web development.

Symfony Associative Array Form Type

12/12/2022

Among the advantages of Symfony, flexibility, and ease of customization are often mentioned. And when it turns out that something can't be done easily, another advantage of this framework comes to the rescue – community support. From time to time I get help from other developers working with Symfony so today is my turn to provide you with a ready-made solution. After all, karma comes back, right? Here's a simple tutorial to create an associative array form type in Symfony.

Some time ago, I was given a task that required creating a form field for editing a property, which was an associative array. To my surprise, Symfony does not present a ready solution for such a case! Since you are reading this article, you may have also encountered this problem. Wanting to save you time, I have prepared a short step-by-step tutorial, which you can find below. I hope you will find it helpful.

1. Create a new FormType for a single array row

In this step, you should add a collection form field in order to keep the array index and value in the respective child forms of the collection form. Let’s first create the new form type, which represents a single key ➡ value row of the array:

class AssociativeArrayItemType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options): void
   {
       $builder
           ->add('key', TextType::class)
           ->add('value', TextType::class)
      ;
   }
}

2. Use the newly created FormType

Now, let's create a form type representing our associative array and use the newly created type as a single entry:

class AssociativeArrayType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       $builder->add('items', CollectionType::class, [
           'entry_type' => AssociativeArrayItemType::class,
           'label' => false,
       ]);
   }
}

3. Add Model transformers

The visual representation is ready. Now you need to implement transforming the associative array into displayable rows and back into the associative array after submit:

class AssociativeArrayType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       ...
       $builder->addModelTransformer(new CallbackTransformer(
           function ($associativeArrayData) {
               $associativeArrayData = $associativeArrayData ?? [];
               $newData = [];
               foreach ($associativeArrayData as $key => $value) {
                   $newData['items'][] = [
                      'key' => $key,
                      'value' => $value
                   ];
              }
              return $newData;
           },
           function ($dtoData) {
               $newData = [];
               foreach ($dtoData['items'] as $item) {
                   $newData[$item['key']] = $item['value'];
               }
               return $newData;
           }
       ));
   }
}

4. Use your new associative array FormType

Now you’re ready to use the new FormType, and you will be easily able to edit associative array data!

class PlanInstallForm extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       ...
      
       $builder
           ->add('handler', ChoiceType::class, [
               'choices' => $handlerChoices,
               'placeholder' => '--- choose handler ---'
           ])
           ->add('params', AssociativeArrayType::class)
       ;
   }
}

5. Customize your AssociativeArrayType

Now, what if you wanted to be able to customize the types of fields that your key and value are? For example, you want the keys to be a ChoiceType with values specified by yourself. Just make it possible to pass it as an option. Do the same with the options of the corresponding field. Let’s configure the array row form, so it is able to receive the mentioned options:

class AssociativeArrayItemType extends AbstractType

{
   public function buildForm(FormBuilderInterface $builder, array $options): void
   {
       $builder
           ->add('key', $options['key_field_type'], $options['key_field_options'])
           ->add(
               'value',
               $options['value_field_type'],
               $options['value_field_options']
           )
       ;
   }
   public function configureOptions(OptionsResolver $resolver): void
   {
       $resolver->setDefaults([
           'key_field_type' => TextType::class,
           'value_field_type' => TextType::class,
           'key_field_options' => [],
           'value_field_options' => [],
       ]);
   }
}

Now let’s make sure, that your main FormType also receives and passes these options down to the children forms:

class AssociativeArrayType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       $builder->add('items', CollectionType::class, [
           'entry_type' => AssociativeArrayItemType::class,
           'entry_options' => $options['item_options'],
           'label' => false,
       ]);
      ...
   }
   public function configureOptions(OptionsResolver $resolver): void
   {
       $resolver->setDefaults([
           'item_options' => [
               'key_field_type' => TextType::class,
               'value_field_type' => TextType::class,
               'key_field_options' => [],
               'value_field_options' => [],
           ],
       ]);
   }
}

Now in order to make the key field a choiceType, you need to pass the desired type and choices in options when using our new FormType:

class PlanInstallForm extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
       ...
       $builder
           ->add('handler', ChoiceType::class, [
               'choices' => $handlerChoices,
               'placeholder' => '--- choose handler ---'
           ])
           ->add('params', AssociativeArrayType::class, [
               'item_options' => [
                   'key_field_type' => ChoiceType::class,
                   'key_field_options' => [
                       'choices' => $paramsChoices,
                   ],
               ],
           ])
       ;
   }
}

6. Allow adding and removing items to the form

I have described how to create a FormType, that automatically handles adding and removing items to a CollectionType in another article:

All you need to do is create the CustomCollectionType and use it instead of the regular CollectionType in your form! Otherwise, you can handle this use case with regular javascript according to the Symfony docs:

Łu
Portrait of Łukasz Traczyk, back-end developer, a professional with a casual and approachable demeanor, wearing a light blue henley shirt. His relaxed, confident smile and neatly groomed beard convey a sense of friendliness and expertise, suitable for an author or staff profile photo.
Łukasz Traczyk
Back-end Developer

Latest articles

Illustration of a woman analyzing financial data with charts, coins, and arrows symbolizing the concept of Fixed Price contracts in technology.

Business | 15/05/2024

Fixed-Price Contract: Benefits for Your Company

Łukasz Kopaczewski

When looking for a Software House to cooperate with, you need to consider many factors. Some of the most important are the price of the services and the method of billing. The two most popular types of contracts are Fixed Price and Time and Material, although you may also encounter a mixed model. Today we will look at the Fixed Price model, which offers stability and predictability to clients.

Read more
Ilustracja pokazująca ludzi współpracujących przy projekcie wykorzystujących Mobile-First Design.

Development | 27/10/2023

Mobile-First Design Strategies

Agata Pater

According to statistics, more than 56% of web traffic is coming from mobile devices. Even though this trend slowed down, it’s still over half of total traffic. Top tech companies noticed that their customers want to have a seamless experience while using their favorite apps and visiting websites. This was the birth of mobile-first design. How thinking about mobile devices can help your business? What are the good practices to implement in your project?

Read more
A vivid illustration of a software development scene with two professionals collaborating on code, surrounded by the Symfony logo and digital motifs, perfect for the service side of a software house.

Business | 20/10/2023

What Is a Software House? The Opportunities of Working with a Software Company

Agata Pater

From custom software development to mobile app creation, from web design to cybersecurity solutions—software houses help thousands of companies build digital products that fuel their work. But what exactly is a software house? In this article, we will delve into the world of software houses, exploring their roles, services, and the essential collaboration between these entities and their clients.

Read more