Skip to content

Commit 40bd267

Browse files
committed
[Form] Documented the setInvalidMessage() method for data mappers
1 parent 09787d3 commit 40bd267

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

form/data_mappers.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ in your form type::
8888
use App\Painting\Color;
8989
use Symfony\Component\Form\AbstractType;
9090
use Symfony\Component\Form\DataMapperInterface;
91+
use Symfony\Component\Form\Exception\TransformationFailedException;
9192
use Symfony\Component\Form\Exception\UnexpectedTypeException;
9293
use Symfony\Component\Form\FormInterface;
9394

@@ -124,6 +125,17 @@ in your form type::
124125
/** @var FormInterface[] $forms */
125126
$forms = iterator_to_array($forms);
126127

128+
// optionally you can validate the data to throw more precise exception errors
129+
$redComponent = $forms['red']->getData();
130+
if (!\is_numeric($redComponent) || $redComponent < 0 || $redComponent > 255) {
131+
$failure = new TransformationFailedException('Expected a RGB color component.');
132+
$failure->setInvalidMessage('Color components should be numeric values in the [0-255] range. {{ value }} is invalid.', [
133+
'{{ value }}' => $redComponent,
134+
]);
135+
136+
throw $failure;
137+
}
138+
127139
// as data is passed by reference, overriding it will change it in
128140
// the form object as well
129141
// beware of type inconsistency, see caution below
@@ -135,6 +147,10 @@ in your form type::
135147
}
136148
}
137149

150+
.. versionadded:: 4.3
151+
152+
The ``setInvalidMessage()`` method was introduced in Symfony 4.3.
153+
138154
.. caution::
139155

140156
The data passed to the mapper is *not yet validated*. This means that your

0 commit comments

Comments
 (0)