0

I understand Drupal 8 ControllerBase implements StringTranslationTrait so we can use $this->t() in Controller class. But I found in Drupal 8 examples code, they setStringTranslation to use t() function. Here is the code.

public static function create(ContainerInterface $container) {
    $controller = new static(
      $container->get('database')
    );
    $controller->setStringTranslation($container->get('string_translation'));
    return $controller;
  }

The link for their module. https://git.drupalcode.org/project/examples/blob/8.x-1.x/tablesort_example/src/Controller/TableSortExampleController.php

My question is why setStringTranslation when you can just use t() function in the controller.

2
  • Most likely the opinion of using the injected container rather than depending on the \Drupal object. It's an opinion. I agree, but I don't agree enough to go out of my way to not use StringTranslationTrait.
    – mradcliffe
    Commented May 16, 2019 at 0:55
  • 1
    You don't need the setter method to instantiate the object, you can inject via constructor. See drupal.stackexchange.com/questions/239239/…
    – 4uk4
    Commented May 16, 2019 at 6:45

1 Answer 1

0

$this->t() assumes object context. $this isn't available in the static context of the create method above.

The ControllerBase provides access to t() via a protected function (see below from docs) to it is also not available from the public context. setStringTranslation however is a publicly available method.

StringTranslationTrait::t   protected   function    Translates a string to the current language or to a given language.
...
StringTranslationTrait::setStringTranslation    public  function    Sets the string translation service to use.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Controller%21ControllerBase.php/class/ControllerBase/8.2.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.