Skip to content

[Form] Documented the setInvalidMessage() method for data transformers #11756

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 21, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions form/data_transformers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,44 @@ and type-hint the new class::
// ...
}

Instead of defining the same ``invalid_message`` every time the form type is
used, you can set the end-user error message in the data transformer using the
``setInvalidMessage()`` method::

// src/Form/DataTransformer/IssueToNumberTransformer.php
namespace App\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class IssueToNumberTransformer implements DataTransformerInterface
{
// ...

public function reverseTransform($issueNumber)
{
// ...

if (null === $issue) {
$privateErrorMessage = sprintf('An issue with number "%s" does not exist!', $issueNumber);
$publicErrorMessage = 'The given "{{ value }}" value is not a valid issue number.';

$failure = new TransformationFailedException($privateErrorMessage);
$failure->setInvalidMessage($publicErrorMessage, [
'{{ value }}' => $issueNumber,
]);

throw $failure;
}

return $issue;
}
}

.. versionadded:: 4.3

The ``setInvalidMessage()`` method was introduced in Symfony 4.3.

That's it! As long as you're using :ref:`autowire <services-autowire>` and
:ref:`autoconfigure <services-autoconfigure>`, Symfony will automatically
know to pass your ``TaskType`` an instance of the ``IssueToNumberTransformer``.
Expand Down