Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions form/data_mappers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,45 @@ method::
Cool! When using the ``ColorType`` form, the custom data mapper methods will
create a new ``Color`` object now.

Mapping Form Fields Using Callbacks
-----------------------------------

Conveniently, you can also map data from and into a form field by using the
``getter`` and ``setter`` options. For example, suppose you have a form with some
fields and only one of them needs to be mapped in some special way or you only
need to change how it's written into the underlying object. In that case, register
a PHP callable that is able to write or read to/from that specific object::

public function buildForm(FormBuilderInterface $builder, array $options)
{
// ...

$builder->add('state', ChoiceType::class, [
'choices' => [
'active' => true,
'paused' => false,
],
'getter' => function (Task $task, FormInterface $form): bool {
return !$task->isCancelled() && !$task->isPaused();
},
'setter' => function (Task &$task, bool $state, FormInterface $form): void {
if ($state) {
$task->activate();
} else {
$task->pause();
}
},
]);
}

If available, these options have priority over the property path accessor and
the default data mapper will still use the :doc:`PropertyAccess component </components/property_access>`
for the other form fields.

.. versionadded:: 5.2

The ``getter`` and ``setter`` options were introduced in Symfony 5.2.

.. caution::

When a form has the ``inherit_data`` option set to ``true``, it does not use the data mapper and
Expand Down