This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
Go to file
Fabien Potencier c34865f175 feature #37968 [Form] Add new way of mapping data using callback functions (yceruto)
This PR was merged into the 5.2-dev branch.

Discussion
----------

[Form] Add new way of mapping data using callback functions

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | yes
| Tickets       | Fix #37597 (partially)
| License       | MIT
| Doc PR        | https://github.com/symfony/symfony-docs/pull/14241

Replaces https://github.com/symfony/symfony/pull/37614

## What this solves

Objects and Forms have different mechanisms for structuring data. When you build an object model with a lot of business logic it's valuable to use these mechanisms to better collect the data and the behavior that goes with it. Doing so leads to variant schemas; that is, the object model schema and the form schema don't match up.

You still need to transfer data between the two schemas, and this data transfer becomes a complexity in its own right. If the objects know about the form structure, changes in one tend to ripple to the other.

Currently, the Data Mapper layer separates the objects from the form, transfering data between the two and also isolating them from each other. That's fine, but at present the default data mapper has a limitation: _it's very tied to one property path_ (see [`PropertyPathMapper`](https://github.com/symfony/symfony/blob/5.1/src/Symfony/Component/Form/Extension/Core/DataMapper/PropertyPathMapper.php)).

That said, you'll have to write your own data mapper in the following situations:
 * When the property path differs for reading and writing
 * When several form fields are mapped to a single method
 * When you need to read data based on the model's state
 * When the mapping of the model depends on the submitted form data
 * ...

Also, when we create a new data mapper, we usually forget about checking the status of the given data and forms. Whether the data is empty or not; throw an exception if the given data is not an object/array and whether the form field is submitted/synchronized/disabled or not. Not doing that could lead to unwanted behavior.

## What this proposes

Create a new way to write and read values to/from an object/array using callback functions. This feature would be tied to each form field and would also mean a new way of mapping data, but a very convenient one, in which it won't be necessary to define a new data mapper and take into account all what it would imply when you only need to map one field in a different manner or perhaps in only one direction (writing or reading the value).

This PR adds two new options for each form type: `getter` and `setter`, allowed to be `null` or `callable`:
```php
$builder->add('name', TextType::class, [
    'getter' => function (Person $person, FormInterface $form): string {
        return $person->firstName().' '.$person->lastName();
    },
    'setter' => function (Person &$person, ?string $name, FormInterface $form): void {
        $person->rename($name);
    },
]);
```
This would give us the same possibilities as data mappers, but within the form field scope, where:
 * `$person` is the view data, basically the underlying data to the form.
 * `$form` is the current child form that is being mapped.
 * `$name` is the submitted data that belongs to that field.

These two callbacks will be executed following the same rules as for property paths before read and write any value (e.i. early return if empty data, skip mapping if the form field is not mapped or it's disabled, etc).

## What this also proposes

I based the implementation on solving this problem first:

> https://github.com/symfony/symfony/pull/37614#issuecomment-662957865
> [...] the property_path option defines the rules on how it's accessed. From there, the actual way it is accessed (direct property access, accessors, reflection, whatever) are hidden from view. All that matters is the property path (which is deduced from the name if not explicitly set). [...]

So splitting the default data mapper `PropertyPathMapper` into two artifacts: "[DataMapper](https://github.com/yceruto/symfony/blob/data_accessor/src/Symfony/Component/Form/Extension/Core/DataMapper/DataMapper.php)" and "[DataAccessor](https://github.com/yceruto/symfony/blob/data_accessor/src/Symfony/Component/Form/DataAccessorInterface.php)" would allow us adding multiple data accessors along the way (the code that varies in this case) without having to reinvent the wheel over and over again (the data mapper code).

You can also think about a new `ReflectionAccessor` for instance? or use this `CallbackAccessor` to map your form partially from an external API? yes, you could do it :)

Here is a view of the proposed changes:

![data_accessor](https://user-images.githubusercontent.com/2028198/91452859-16bf8f00-e84d-11ea-8564-d497c2f73730.png)

Where "DataMapper" will take care of common checks, iterates the given child forms, manages the form data and all what is needed for mapping a standard form, whereas "DataAccessor" will take care of how to read and write values to/from the underlying object or array.

## BC

The `PropertyPathMapper` is being deprecated in favor of `DataMapper` class, which uses the `PropertyPathAccessor` by default.

Although `DataMapper` is now the default for each compound form, the behavior must remains the same (tests prove it). So that if `getter` or `setter` option is null (they're by default) the `CallbackAccessor` will falls back to `PropertyPathAccessor` either for reading or writing values.

---

Sorry for the long description, but I think that sometimes it is necessary for too complex issues and big changes. Besides, now you know a little more about what these changes is about.

/cc @xabbuh as creator of [rich-model-forms-bundle](https://github.com/sensiolabs-de/rich-model-forms-bundle) and @alcaeus as you had worked on this issue.

WDYT?

Commits
-------

878effaf47 add new way of mapping data using callback functions
2020-09-16 14:32:39 +02:00
.github Ignore attribute fixtures when patching types. 2020-09-14 09:33:07 +02:00
src/Symfony feature #37968 [Form] Add new way of mapping data using callback functions (yceruto) 2020-09-16 14:32:39 +02:00
.appveyor.yml Merge branch '5.0' 2020-04-12 11:49:11 +02:00
.editorconfig Update .editorconfig 2018-09-06 16:22:56 +02:00
.gitignore Run the phpunit-bridge from a PR 2019-08-02 17:46:19 +02:00
.php_cs.dist Merge branch '5.1' 2020-09-02 18:27:44 +02:00
.travis.yml Merge branch '4.4' into 5.1 2020-09-07 14:08:23 +02:00
CHANGELOG-4.0.md Merge branch '3.4' into 4.1 2018-08-01 18:22:14 +02:00
CHANGELOG-4.1.md updated CHANGELOG for 4.1.10 2019-01-06 17:16:07 +01:00
CHANGELOG-4.2.md updated CHANGELOG for 4.2.10 2019-06-26 16:19:37 +02:00
CHANGELOG-4.3.md updated CHANGELOG for 4.3.10 2020-01-21 14:13:32 +01:00
CHANGELOG-4.4.md Update CHANGELOG for 4.4.13 2020-09-02 10:09:24 +02:00
CHANGELOG-5.0.md Merge branch '5.0' into 5.1 2020-06-15 13:50:15 +02:00
CHANGELOG-5.1.md Update CHANGELOG for 5.1.5 2020-09-02 10:15:01 +02:00
CODE_OF_CONDUCT.md Added the Code of Conduct file 2018-10-10 03:13:30 -07:00
composer.json bug #37578 [HttpClient] fix pausing AmpResponse (kelunik) 2020-08-27 16:48:24 +02:00
CONTRIBUTING.md Mention the community review guide 2016-12-18 22:02:35 +01:00
CONTRIBUTORS.md Update CONTRIBUTORS for 3.4.44 2020-08-31 07:52:54 +02:00
LICENSE Update year in license files 2020-01-01 12:03:25 +01:00
link Merge branch '3.4' into 4.4 2020-08-26 10:30:46 +02:00
phpunit Use PHPUnit 9.3 on php 8. 2020-08-10 10:16:22 +02:00
phpunit.xml.dist [Uid] minor improvements 2020-03-20 20:42:05 +01:00
README.md Minor improvement 2020-07-29 07:57:47 +02:00
UPGRADE-5.0.md Typo: somes styles fixed 2020-08-06 09:00:23 +02:00
UPGRADE-5.1.md Update UPGRADE-5.1.md 2020-09-07 01:58:27 +02:00
UPGRADE-5.2.md add new way of mapping data using callback functions 2020-09-15 10:00:10 -04:00
UPGRADE-6.0.md add new way of mapping data using callback functions 2020-09-15 10:00:10 -04:00

Symfony is a PHP framework for web and console applications and a set of reusable PHP components. Symfony is used by thousands of web applications (including BlaBlaCar.com and Spotify.com) and most of the popular PHP projects (including Drupal and Magento).

Installation

Documentation

Community

Contributing

Symfony is an Open Source, community-driven project with thousands of contributors. Join them contributing code or contributing documentation.

Security Issues

If you discover a security vulnerability within Symfony, please follow our disclosure procedure.

About Us

Symfony development is sponsored by SensioLabs, led by the Symfony Core Team and supported by Symfony contributors.