Skip to content

Commit e297daa

Browse files
committed
Explain trigger errors from DataMapper
Symfony allows the user to send a form error from the DataMapper in case the data does not fit the object. This powerful feature was not documented.
1 parent 8278533 commit e297daa

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

form/data_mappers.rst

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,55 @@ create a new ``Color`` object now.
193193

194194
When a form has the ``inherit_data`` option set to ``true``, it does not use the data mapper and
195195
lets its parent map inner values.
196+
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)