Sister issue of #2608738: Add a warning for \Drupal:: use in OO code.

t() should not be used in a controller class or a form class or a plugin class. Dependency injection should be used instead.

Wrong:

class TestForm extends FormBase {

  public function buildForm($form, $form_state) {
    $form['something'] = t('Example text');
  }

}

Correct:

class TestForm extends FormBase {

  public function buildForm($form, $form_state) {
    $form['something'] = $this->t('Example text');
  }

}

Comments

klausi created an issue. See original summary.

  • klausi committed cca42ac on 8.x-2.x
    Issue #2720343: Add a warning for global function use like t() in...
klausi’s picture

Other functions commonly used that we should add?

dawehner’s picture

Note: t() might be still the common way in static methods like Entity::baseFieldDefinitions

Here is a list of more methods:

  • format_string
  • drupal_get_destination()
  • format_date
  • drupal_render
klausi’s picture

another example: Term::loadMultiple() and similar calls on Node:: or User:: for example.

  • klausi committed 43d37dc on 8.x-2.x
    Issue #2720343: Added a sniff for global class calls such Node::load()...

  • klausi committed 6d717e1 on 8.x-2.x
    Isssue #2720343: Allow global t() and \Drupal calls in static methods
    

  • klausi committed 74cba83 on 8.x-2.x
    fix(GlobalFunctionSniff): Add more deprecated global functions that...
klausi’s picture

Status: Active » Fixed

Committed some more functions with their replacements. I think we can call this fixed now and add further functions on demand.

We also have #2647462: Include warnings about deprecated functions and methods open for stuff that is deprecated in general.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.