@@ -124,13 +124,27 @@ in your form type::
124
124
/** @var FormInterface[] $forms */
125
125
$forms = iterator_to_array($forms);
126
126
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
+
127
141
// as data is passed by reference, overriding it will change it in
128
142
// the form object as well
129
143
// beware of type inconsistency, see caution below
130
144
$viewData = new Color(
131
- $forms ['red']->getData() ,
132
- $forms ['green']->getData() ,
133
- $forms ['blue']->getData()
145
+ $colors ['red'],
146
+ $colors ['green'],
147
+ $colors ['blue']
134
148
);
135
149
}
136
150
}
@@ -193,55 +207,3 @@ create a new ``Color`` object now.
193
207
194
208
When a form has the ``inherit_data `` option set to ``true ``, it does not use the data mapper and
195
209
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