From 53fb3c73582b0fd1897b29098f89a871f628b7f8 Mon Sep 17 00:00:00 2001 From: Yonel Ceruto Date: Tue, 15 Sep 2020 01:19:38 -0400 Subject: [PATCH] Add new way of mapping form data --- form/data_mappers.rst | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/form/data_mappers.rst b/form/data_mappers.rst index 15e66ce54b3..24a0f41d39e 100644 --- a/form/data_mappers.rst +++ b/form/data_mappers.rst @@ -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 ` +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