While creating Form in Laminas I want to know translate the Form Labels. One way is I pass the translator to the form, is there a better way of translation and how does it get the language of the currently logged in user in Form?Also which view helper is used for translation?
I assume that you are using a laminas-mvc based application.
Add translation files and configuration for the translator to the application configuration. Example:
return [ 'translator' => [ 'translation_files' => [ [ 'type' => Laminas\I18n\Translator\Loader\PhpArray::class, 'filename' => __DIR__ . '/data/languages/en/example.php', 'locale' => 'en_EN', ], // … ], 'translation_file_patterns' => [ [ 'type' => Laminas\I18n\Translator\Loader\PhpArray::class, 'base_dir' => Laminas\I18n\Translator\Resources::getBasePath(), 'pattern' => Laminas\I18n\Translator\Resources::getPatternForValidator(), ], ], 'event_manager_enabled' => true, ], // … ];
- Set the locale.
First: The forms are irrelevant, the translation is done outside the forms, at the view layer.
There are several ways to set and get the locale. Therefore, it depends on what you use in your application. Do you use laminas-authentication or something else?
The form view helpers extends the abstract view helper of laminas-i18n, which uses the translator of your application (injected via the view helper plugin manager of laminas-view).
I understand the fields are still added in the form which has also the untranslated labels; the only thing is these labels are translated later in view? Also please discuss what are the benefits in following this new approach. Thanks!
Correct, labels are added as untranslated strings and the form view helpers use the translator to translated them.
This is not a new approach, this is the normal way. It is not necessary to pass around a translator instance. If you use the MVC integration of laminas-i18n then laminas-view and laminas-form will use it and therefore you do not have to do more. The components interact here and therefore this approach is sufficient.
How do you attach validators to the form elements ?
New topic, please create a new post. (This helps other users to find the different topics more easily.)
Thanks in advance!