Search code examples
drupaldrupal-8

override FieldPluginBase init function Drupal


is it possible to inject a custom service into a class which extends FieldPluginBase ?

  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->currentDisplay = $view->current_display;
  }

When I try to inject one of my services I get that error :

Fatal error: Declaration of Drupal\xxx_api\Plugin\views\field\NewsViewsField::init(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\display\DisplayPluginBase $display, ?array &$options, Drupal\xxx_api\Service\ArticleService $articleService) must be compatible with Drupal\views\Plugin\views\field\FieldPluginBase::init(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\display\DisplayPluginBase $display, ?array &$options = NULL)

Thanks by advance for helping :)


Solution

  • Yes this is possible, but you should inject it either in the constructor or via the create() method.

    In the same views core module of which you are extending the FieldPluginBase class from there is a RenderedEntity class which is a good example that does so.

    So in your case this could look like something in the below. Note that I have used YourService as a placeholder for the service that you are trying to inject:

    namespace Drupal\xxx_api\Plugin\views\field;
    
    /**
     * Example Views field.
     *
     * @ViewsField("news_views_field")
     */
    class NewsViewsField extends FieldPluginBase {
    
      /**
       * Your Service interface.
       *
       * @var \Drupal\foo\YourServiceInterface
       */
      protected $yourService;
    
      /**
       * Constructs a NewsViewsField object.
       *
       * @param array $configuration
       *   A configuration array containing information about the plugin instance.
       * @param string $plugin_id
       *   The plugin_id for the plugin instance.
       * @param mixed $plugin_definition
       *   The plugin implementation definition.
       * @param \Drupal\foo\YourServiceInterface $your_service
       *   Your Service.
       */
      public function __construct(array $configuration, $plugin_id, $plugin_definition, YourServiceInterface $your_service) {
        parent::__construct($configuration, $plugin_id, $plugin_definition);
        // Inject your service.
        $this->yourService = $your_service;
      }
    
      /**
       * {@inheritdoc}
       */
      public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static(
          $configuration,
          $plugin_id,
          $plugin_definition,
          // Add your service here to pass an instance to the constructor.
          $container->get('your.service')
        );
      }
    
      ...
    
    }