Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. When and How to Use Data Mappers
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • The Difference between Data Transformers and Mappers
  • Creating a Data Mapper
  • Using the Mapper

When and How to Use Data Mappers

Edit this page

Warning: You are browsing the documentation for Symfony 3.4, which is no longer maintained.

Read the updated version of this page for Symfony 6.3 (the current stable version).

When and How to Use Data Mappers

When a form is compound, the initial data needs to be passed to children so each can display their own input value. On submission, children values need to be written back into the form.

Data mappers are responsible for reading and writing data from and into parent forms.

The main built-in data mapper uses the PropertyAccess component and will fit most cases. However, you can create your own implementation that could, for example, pass submitted data to immutable objects via their constructor.

The Difference between Data Transformers and Mappers

It is important to know the difference between data transformers and mappers.

  • Data transformers change the representation of a value (e.g. from "2016-08-12" to a DateTime instance);
  • Data mappers map data (e.g. an object or array) to form fields, and vice versa.

Changing a YYYY-mm-dd string value to a DateTime instance is done by a data transformer. Populating inner fields (e.g year, hour, etc) of a compound date type using a DateTime instance is done by the data mapper.

Creating a Data Mapper

Suppose that you want to save a set of colors to the database. For this, you're using an immutable color object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// src/AppBundle/Painting/Color.php
namespace AppBundle\Painting;

final class Color
{
    private $red;
    private $green;
    private $blue;

    public function __construct(int $red, int $green, int $blue)
    {
        $this->red = $red;
        $this->green = $green;
        $this->blue = $blue;
    }

    public function getRed(): int
    {
        return $this->red;
    }

    public function getGreen(): int
    {
        return $this->green;
    }

    public function getBlue(): int
    {
        return $this->blue;
    }
}

The form type should be allowed to edit a color. But because you've decided to make the Color object immutable, a new color object has to be created each time one of the values is changed.

Tip

If you're using a mutable object with constructor arguments, instead of using a data mapper, you should configure the empty_data option with a closure as described in How to Configure empty Data for a Form Class.

The red, green and blue form fields have to be mapped to the constructor arguments and the Color instance has to be mapped to red, green and blue form fields. Recognize a familiar pattern? It's time for a data mapper. The easiest way to create one is by implementing DataMapperInterface in your form type:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// src/AppBundle/Form/ColorType.php
namespace AppBundle\Form;

use AppBundle\Painting\Color;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\FormInterface;

final class ColorType extends AbstractType implements DataMapperInterface
{
    // ...

    /**
     * @param Color|null $viewData
     */
    public function mapDataToForms($viewData, $forms)
    {
        // there is no data yet, so nothing to prepopulate
        if (null === $viewData) {
            return;
        }

        // invalid data type
        if (!$viewData instanceof Color) {
            throw new UnexpectedTypeException($viewData, Color::class);
        }

        /** @var FormInterface[] $forms */
        $forms = iterator_to_array($forms);

        // initialize form field values
        $forms['red']->setData($viewData->getRed());
        $forms['green']->setData($viewData->getGreen());
        $forms['blue']->setData($viewData->getBlue());
    }

    public function mapFormsToData($forms, &$viewData)
    {
        /** @var FormInterface[] $forms */
        $forms = iterator_to_array($forms);

        // as data is passed by reference, overriding it will change it in
        // the form object as well
        // beware of type inconsistency, see caution below
        $viewData = new Color(
            $forms['red']->getData(),
            $forms['green']->getData(),
            $forms['blue']->getData()
        );
    }
}

Caution

The data passed to the mapper is not yet validated. This means that your objects should allow being created in an invalid state in order to produce user-friendly errors in the form.

Using the Mapper

After creating the data mapper, you need to configure the form to use it. This is achieved using the setDataMapper() method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/AppBundle/Form/Type/ColorType.php

// ...
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

final class ColorType extends AbstractType implements DataMapperInterface
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('red', IntegerType::class, [
                // enforce the strictness of the type to ensure the constructor
                // of the Color class doesn't break
                'empty_data' => '0',
            ])
            ->add('green', IntegerType::class, [
                'empty_data' => '0',
            ])
            ->add('blue', IntegerType::class, [
                'empty_data' => '0',
            ])
            // configure the data mapper for this FormType
            ->setDataMapper($this)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        // when creating a new color, the initial data should be null
        $resolver->setDefault('empty_data', null);
    }

    // ...
}

Cool! When using the ColorType form, the custom data mapper methods will create a new Color object now.

Caution

When a form has the inherit_data option set to true, it does not use the data mapper and lets its parent map inner values.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Take the exam at home

    Take the exam at home

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Hassan Amouhzi, a Symfony contributor

    Thanks Hassan Amouhzi for being a Symfony contributor

    4 commits • 53 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Meilisearch