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 that symbolizes the importance of governance in ESG

Business | 15/11/2024

Governance in ESG: Why Strong Leadership is Key to Sustainability?

Łukasz Kopaczewski

While all three pillars—environmental, social, and governance—are essential, governance often plays the most foundational role. Governance, which includes ethical leadership, transparency, and accountability, ensures that ESG efforts are not just statements on paper but integrated into a company’s everyday decisions. Notably, a recent study found that 39% of companies feel they perform adequately on governance, indicating significant room for improvement​.

Read more
Illustration to the article on Making Data-Driven Decision and AI

Business | 08/11/2024

Making Data-Driven Decisions: How Artificial Intelligence Can Help You Avoid Common Pitfalls

Agata Pater

Relying solely on intuition in business can often mean missing out on big opportunities. Consider Netflix as a prime example. By analyzing over 30 million daily 'plays' and countless subscriber ratings and searches, Netflix pinpointed exactly what viewers wanted, leading to the creation of hit series like House of Cards. This data-driven approach didn’t just increase viewer engagement; it revolutionized the entertainment industry’s approach to content creation. Embracing Data-Driven Decision Making can similarly empower companies to craft more precise strategies, avoid common pitfalls, and make choices that resonate with actual market demand.

Read more
Illustration to the article about importance of ESG factors in construction sector, and how AI can help in reporting sustainability efforts.

Business | 31/10/2024

The Growing Importance of ESG in Construction Industry

Bernhard Huber

The construction industry is a critical driver of economic growth, responsible for creating the infrastructure that supports communities and industries worldwide. However, this sector also faces substantial challenges related to environmental degradation, social equity, and governance issues. Increasing global awareness of climate change, heightened investor scrutiny, and evolving regulatory demands have led to a fundamental shift in how construction companies approach their operations.

Read more