Skip to content

[Validator] Add "Translatable Objects" example #19054

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
Oct 25, 2023
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
23 changes: 23 additions & 0 deletions validation/translations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,29 @@ Now, create a ``validators`` catalog file in the ``translations/`` directory:
You may need to clear your cache (even in the dev environment) after creating
this file for the first time.

You can also use :class:`Symfony\\Component\\Translation\\TranslatableMessage` to build your violation message::

use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

#[Assert\Callback]
public function validate(ExecutionContextInterface $context, mixed $payload): void
{
// somehow you have an array of "fake names"
$fakeNames = [/* ... */];

// check if the name is actually a fake name
if (in_array($this->getFirstName(), $fakeNames, true)) {
$context->buildViolation(new TranslatableMessage('author.name.fake', [], 'validators'))
->atPath('firstName')
->addViolation()
;
}
}

You can learn more about translatable messages in :ref:`the dedicated section <translatable-objects>`.

Custom Translation Domain
-------------------------

Expand Down