1

I need to inject a service inside a block. Since I need some logic before displaying the block, it feels dirty to do it inside the block itself, not to mention it's not actually related to the block itself.

Normally I'd inject a service by using the create() method available in the controller, but blocks don't seem to have this method.

How do I use a service from a block?

3

You do it the same way, the only difference is that you need to make your block class aware of the container first.

Example:

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
...
class FooBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $aliasManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AliasManagerInterface $alias_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->aliasManager = $alias_manager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('path.alias_manager')
    );
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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