When and How to Use Data Mappers

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. // src/Painting/Color.php
  2. namespace App\Painting;
  3. final class Color
  4. {
  5. private $red;
  6. private $green;
  7. private $blue;
  8. public function __construct(int $red, int $green, int $blue)
  9. {
  10. $this->red = $red;
  11. $this->green = $green;
  12. $this->blue = $blue;
  13. }
  14. public function getRed(): int
  15. {
  16. return $this->red;
  17. }
  18. public function getGreen(): int
  19. {
  20. return $this->green;
  21. }
  22. public function getBlue(): int
  23. {
  24. return $this->blue;
  25. }
  26. }

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 Symfony\Component\Form\DataMapperInterface in your form type:

  1. // src/Form/ColorType.php
  2. namespace App\Form;
  3. use App\Painting\Color;
  4. use Symfony\Component\Form\AbstractType;
  5. use Symfony\Component\Form\DataMapperInterface;
  6. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  7. use Symfony\Component\Form\FormInterface;
  8. final class ColorType extends AbstractType implements DataMapperInterface
  9. {
  10. // ...
  11. /**
  12. * @param Color|null $viewData
  13. */
  14. public function mapDataToForms($viewData, $forms): void
  15. {
  16. // there is no data yet, so nothing to prepopulate
  17. if (null === $viewData) {
  18. return;
  19. }
  20. // invalid data type
  21. if (!$viewData instanceof Color) {
  22. throw new UnexpectedTypeException($viewData, Color::class);
  23. }
  24. /** @var FormInterface[] $forms */
  25. $forms = iterator_to_array($forms);
  26. // initialize form field values
  27. $forms['red']->setData($viewData->getRed());
  28. $forms['green']->setData($viewData->getGreen());
  29. $forms['blue']->setData($viewData->getBlue());
  30. }
  31. public function mapFormsToData($forms, &$viewData): void
  32. {
  33. /** @var FormInterface[] $forms */
  34. $forms = iterator_to_array($forms);
  35. // as data is passed by reference, overriding it will change it in
  36. // the form object as well
  37. // beware of type inconsistency, see caution below
  38. $viewData = new Color(
  39. $forms['red']->getData(),
  40. $forms['green']->getData(),
  41. $forms['blue']->getData()
  42. );
  43. }
  44. }

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()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Form/FormConfigBuilderInterface.php "Symfony\Component\Form\FormConfigBuilderInterface::setDataMapper()") method:

  1. // src/Form/Type/ColorType.php
  2. namespace App\Form\Type;
  3. // ...
  4. use Symfony\Component\Form\Extension\Core\Type\IntegerType;
  5. use Symfony\Component\Form\FormBuilderInterface;
  6. use Symfony\Component\OptionsResolver\OptionsResolver;
  7. final class ColorType extends AbstractType implements DataMapperInterface
  8. {
  9. public function buildForm(FormBuilderInterface $builder, array $options): void
  10. {
  11. $builder
  12. ->add('red', IntegerType::class, [
  13. // enforce the strictness of the type to ensure the constructor
  14. // of the Color class doesn't break
  15. 'empty_data' => '0',
  16. ])
  17. ->add('green', IntegerType::class, [
  18. 'empty_data' => '0',
  19. ])
  20. ->add('blue', IntegerType::class, [
  21. 'empty_data' => '0',
  22. ])
  23. // configure the data mapper for this FormType
  24. ->setDataMapper($this)
  25. ;
  26. }
  27. public function configureOptions(OptionsResolver $resolver): void
  28. {
  29. // when creating a new color, the initial data should be null
  30. $resolver->setDefault('empty_data', null);
  31. }
  32. // ...
  33. }

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.