首页 > 解决方案 > 覆盖 FieldPluginBase 初始化函数 Drupal

问题描述

是否可以将自定义服务注入到扩展 FieldPluginBase 的类中?

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

当我尝试注入我的一项服务时,我得到了这个错误:

致命错误: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) 必须与 Drupal\views\Plugin\views\field\FieldPluginBase::init(Drupal\views\ViewExecutable $view, Drupal\views\Plugin\views\display\DisplayPluginBase $display, ?数组 &$options = NULL)

提前感谢您的帮助:)

标签: drupaldrupal-8

解决方案


是的,这是可能的,但您应该在构造函数中或通过create()方法注入它。

views在您从中扩展类的同一个核心模块中,FieldPluginBase有一个RenderedEntity类是一个很好的例子。

因此,在您的情况下,这可能如下所示。请注意,我已将YourService您尝试注入的服务用作占位符:

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')
    );
  }

  ...

}

推荐阅读