Skip to content

Commit ab0dd30

Browse files
committed
Update feature documentation after @wouterj review
PR symfony#13513
1 parent e297daa commit ab0dd30

File tree

1 file changed

+14
-51
lines changed

1 file changed

+14
-51
lines changed

form/data_mappers.rst

Lines changed: 14 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,20 @@ in your form type::
124124
/** @var FormInterface[] $forms */
125125
$forms = iterator_to_array($forms);
126126

127+
$colors = [
128+
'red' => $forms['red']->getData(),
129+
'green' => $forms['green']->getData(),
130+
'blue' => $forms['blue']->getData(),
131+
];
132+
133+
// TransformationFailedException will be transformed into a FormError
134+
foreach ($colors as $name => $color) {
135+
if ($color > 256 || $color < 0) {
136+
throw new TransformationFailedException(sprintf('Invalid color %s "%s" value', $name, $color));
137+
}
138+
}
139+
140+
127141
// as data is passed by reference, overriding it will change it in
128142
// the form object as well
129143
// beware of type inconsistency, see caution below
@@ -194,54 +208,3 @@ create a new ``Color`` object now.
194208
When a form has the ``inherit_data`` option set to ``true``, it does not use the data mapper and
195209
lets its parent map inner values.
196210

197-
Trigger form errors from the DataMapper
198-
---------------------------------------
199-
200-
You may want to validate the form data to be sure it is conform to the API of your object. In this
201-
case Symfony provides an exception ``TransformationFailedException`` that will result in a FormError
202-
in the case it is throwed during the process::
203-
204-
// src/Form/Type/ColorType.php
205-
namespace App\Form\Type;
206-
207-
// ...
208-
use Symfony\Component\Form\Exception\TransformationFailedException;
209-
210-
final class ColorType extends AbstractType implements DataMapperInterface
211-
{
212-
// ...
213-
214-
public function mapFormsToData($forms, &$viewData)
215-
{
216-
/** @var FormInterface[] $forms */
217-
$forms = iterator_to_array($forms);
218-
219-
$colors = [
220-
'red' => $forms['red']->getData(),
221-
'green' => $forms['green']->getData(),
222-
'blue' => $forms['blue']->getData(),
223-
];
224-
225-
foreach ($colors as $name => $color) {
226-
if ($color > 256 || $color < 0) {
227-
throw new TransformationFailedException(sprintf('Invalid color %s "%s" value', $name, $color));
228-
}
229-
}
230-
231-
// as data is passed by reference, overriding it will change it in
232-
// the form object as well
233-
// beware of type inconsistency, see caution below
234-
$viewData = new Color(
235-
$colors['red'],
236-
$colors['green'],
237-
$colors['blue']
238-
);
239-
}
240-
241-
// ...
242-
}
243-
244-
Aweome! You are now sure to not get an error while instantiating the ``Color`` object, and the error is properly
245-
given to the user via form errors.
246-
247-

0 commit comments

Comments
 (0)