@@ -193,3 +193,55 @@ create a new ``Color`` object now.
193
193
194
194
When a form has the ``inherit_data `` option set to ``true ``, it does not use the data mapper and
195
195
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