I have translator labels in form types, for example:
$builder->add('island', EntityType::class, [
'class' => Island::class,
'choices' => $options['islands'],
'choice_attr' => function(Island $choice) {
// TODO move to template
return ['data-content' => $choice->getParent()
? '<span> ' . $choice->getName() . '</span>'
: '<b>' . $choice->getName() . '</b>'
];
},
'choice_label' => 'name',
'attr' => ['class' => 'selectpicker', 'title' => _('form.cafe.island.title')],
'required' => true,
'label' => false
])
as You can see, I tried with the traditional _() way, with no success.
I tried to generate the new labels in the po file for poedit like this:
php bin/console translation:update --output-format=po --force hu
Any advice or idea is more than welcome.
Thanks in advance!
Best Practice is to not translate in form Type class. Try to put untranslated tag there, and translate in template. This not resolve problem with autogenerate '.po' files, but simplifies Type class, ie. not need to inject translator, not need to translate in every FormType class with title attribute field. Otherwise it requires to put translator and translate attributes in every Type class in the future.
Translate form filed attribute in template, require overloading build-in form template as described in Creating your Own Form Theme.
To simplify process in this case:
Copy block widget_attributes
from build-in template thatis used to own clean template. ie.: templates/form/my_theme.html.twig
Add dthis template to config/packages/twig.yaml
in tag form_themes
, ie.:
twig:
form_themes: ['form/my_theme.html.twig']
add content to this template with extend
original template
{% extends 'bootstrap_3_horizontal_layout.html.twig' %}
and overload block widget_attributes
{% block widget_attributes -%}
{% if attr.title is not empty %}
{% set attr = attr|merge({title: attr.title|trans({}, translation_domain)}) %}
{{ parent() }}
{%- endblock widget_attributes %}
By this approach, we need change in one place and get translation for all title attributes in form fields.
As I said, this do not resolve autogenerate '.po' files, because generator do can't get translation tags from PHP classes. It works only with template files.
And worth noting that not every form widget templates use widget_attribute
to format field attributes, so in some cases it needs to overload specific widget template blok.