In Drupal 8, it seems as though object-oriented code is encouraged to use $this->t()
instead of the global function t()
, by either adding StringTranslationTrait
to the class, or extending a core class (eg. a plugin, controller or form) that has it.
If I understand correctly, this is to encapsulate localization and eg. translate particular objects to specific languages without affecting the global scope?
I have a particular subform that occurs both as part of a full form (in a routing path) and as part of a Filter plugin's settings. To accomplish this, I made the subform builder a static function inside the main form, allowing the filter plugin to call it directly. (Both the settings form and the main form add other fields in addition to the subform.)
Now, even though the subform function is static, it's only invoked in one of two non-static contexts (extended from FilterBase and ConfigFormBase, respectively, both of which inherit the StringTranslationTrait).
It seems as though the right thing here is to pass the caller's object to the static function, and then use that caller's t() function.
Call 1:
public function buildForm(array $form, FormStateInterface $form_state) {
[...]
$form = self::buildFormHandlers($form, $defaults, $this);
Call 2:
public function settingsForm(array $form, FormStateInterface $form_state) {
[...]
$form = XBBCodeHandlerForm::buildFormHandlers($form, $this->tag_settings, $this);
Definition:
public static function buildFormHandlers(array $form, array $defaults, $caller) {
// Add form fields:
[...]
'#title' => $caller->t('Tag settings'),
It looks like a weird pattern, though, so I'm wondering if I'm missing the point, or overthinking it.