The forms created with the Symfony Form component translate their labels and help messages automatically. However, the translations cannot contain any custom parameters because in the templates, the trans() Twig filter is called without passing any parameters.
In Symfony 4.3 we improved the translation of Symfony Forms allowing to define
custom translation parameters using three new config options:
label_translation_parameters
, help_translation_parameters
, and
attr_translation_parameters
(this one is useful to translate placeholder
and title
):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class OrderType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('comment', TextType::class, [
'label' => 'Comment for the order of %company%',
'label_translation_parameters' => [
'%company%' => 'Acme Ltd.',
],
'help' => 'The address of %company% is %address%',
'help_translation_parameters' => [
'%company%' => 'Acme Ltd.',
'%address%' => '4 Form street, Symfonyville',
],
])
}
}
How do you extract such strings for translation? When using gettext, the extractor can run simple static analysis to find _() function calls.
Really useful!
Just miss a config-based option to add the "raw" filter after "trans" and it'll be perfect 👍
@Josef you cannot extract them using the tools provided for Symfony (which only extract from templates).
@Alex there's a new option in Symfony 4.3 called "help_html". Set it to "true" to output HTML contents as "raw". But I think there's no such option for "label".
@Javier Eguiluz: That sounds like a bug (by design).
@Josef: Just set the t10n directly with a gettext call and set the translation domains to
false
? For more complex t10n (like translating translation parameters) you'd still inject the Translator into the FormType.Matthias: The question is not how to use gettext. The question is how to translate the messages that are used in the source code. The biggest problem is in how to be sure that all the messages are translated. How can I get a PO file from source code such as this example and then send it to a translator who knows other language?