Skip to content

Commit ef0d084

Browse files
authored
Update translations.rst
1 parent 9831a44 commit ef0d084

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

validation/translations.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,40 @@ 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+
Translatable Objects
127+
--------------------
128+
129+
In some cases, you may want to translate content from a simple function with multiple checks or contexts.
130+
For example, when using the ``Callback`` constraints.
131+
132+
You can use the :class:`Symfony\\Component\\Translation\\TranslatableMessage` class like this:
133+
134+
.. configuration-block::
135+
136+
.. code-block:: php-attributes
137+
138+
use Symfony\Component\Translation\TranslatableMessage;
139+
use Symfony\Component\Validator\Constraints as Assert;
140+
use Symfony\Component\Validator\Context\ExecutionContextInterface;
141+
142+
#[Assert\Callback]
143+
public function validate(ExecutionContextInterface $context, mixed $payload): void
144+
{
145+
// somehow you have an array of "fake names"
146+
$fakeNames = [/* ... */];
147+
148+
// check if the name is actually a fake name
149+
if (in_array($this->getFirstName(), $fakeNames)) {
150+
$context->buildViolation(new TranslatableMessage('author.name.fake', [], 'validators'))
151+
->atPath('firstName')
152+
->addViolation()
153+
;
154+
}
155+
}
156+
157+
Learn more about
158+
:ref:`translatable object <translatable-objects>`.
159+
126160
Custom Translation Domain
127161
-------------------------
128162

0 commit comments

Comments
 (0)