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

preview illustration with icons representing education and technology

Innovations | 11/09/2024

Use of Technology in Education: How Is It Bridging the Educational Gap?

Agata Pater

The barriers that once defined educational access—geographical location, economic status, and availability of resources—are gradually being dismantled. As we continue to innovate and implement new technologies, the gaps that have traditionally separated students around the world are closing, bringing us closer to an era of truly equitable education.

Read more
Illustration for the article about AI and sustainable energy

Innovations | 05/09/2024

Revolutionizing the Energy Sector: The Role of AI in Clean and Renewable Energy Transition

Bernhard Huber

As the global community grapples with the challenges of climate change, the shift towards renewable energy sources has never been more critical. The transition to clean energy is not only essential for reducing carbon emissions but also for ensuring a responsible future for generations to come. At the forefront of this revolution is artificial intelligence (AI), a powerful tool that is transforming how we produce, distribute, and consume energy. AI technologies are increasingly being integrated into the energy system, optimizing everything from energy generation to energy storage, and paving the way for a more efficient and resilient energy infrastructure.

Read more
Preview image for the article about AI for social good

Innovations | 30/08/2024

AI for Social Good: Using AI for Positive Social Impact

Bernhard Huber

Artificial Intelligence is rapidly transforming industries and society, offering innovative solutions to complex challenges. The concept of "AI for Social Good" harnesses this technology to address societal issues, from healthcare and education to environmental sustainability and poverty alleviation. As AI continues to evolve, it is crucial to explore its potential for creating a positive social impact and consider the ethical implications of its deployment. By using AI effectively, we can deliver positive social outcomes and tackle some of the most pressing global challenges.

Read more