Skip to content

Commit 56c3af1

Browse files
committed
minor #19054 [Validator] Add "Translatable Objects" example (cavasinf)
This PR was submitted for the 6.4 branch but it was squashed and merged into the 6.3 branch instead. Discussion ---------- [Validator] Add "Translatable Objects" example Resolve #19049 Commits ------- 3b18682 [Validator] Add "Translatable Objects" example
2 parents 0bd175f + 3b18682 commit 56c3af1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

validation/translations.rst

+23
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,29 @@ Now, create a ``validators`` catalog file in the ``translations/`` directory:
123123
You may need to clear your cache (even in the dev environment) after creating
124124
this file for the first time.
125125

126+
You can also use :class:`Symfony\\Component\\Translation\\TranslatableMessage` to build your violation message::
127+
128+
use Symfony\Component\Translation\TranslatableMessage;
129+
use Symfony\Component\Validator\Constraints as Assert;
130+
use Symfony\Component\Validator\Context\ExecutionContextInterface;
131+
132+
#[Assert\Callback]
133+
public function validate(ExecutionContextInterface $context, mixed $payload): void
134+
{
135+
// somehow you have an array of "fake names"
136+
$fakeNames = [/* ... */];
137+
138+
// check if the name is actually a fake name
139+
if (in_array($this->getFirstName(), $fakeNames, true)) {
140+
$context->buildViolation(new TranslatableMessage('author.name.fake', [], 'validators'))
141+
->atPath('firstName')
142+
->addViolation()
143+
;
144+
}
145+
}
146+
147+
You can learn more about translatable messages in :ref:`the dedicated section <translatable-objects>`.
148+
126149
Custom Translation Domain
127150
-------------------------
128151

0 commit comments

Comments
 (0)