【问题标题】:override FieldPluginBase init function Drupal覆盖 FieldPluginBase 初始化函数 Drupal
【发布时间】:2020-09-29 16:00:05
【问题描述】:

是否可以将自定义服务注入到扩展 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 $显示, ?array &$options = NULL)

提前感谢您的帮助:)

【问题讨论】:

    标签: drupal drupal-8


    【解决方案1】:

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

    在您从其扩展 FieldPluginBase 类的同一 views 核心模块中,有一个 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')
        );
      }
    
      ...
    
    }
    

    【讨论】:

    • 非常感谢,这正是我想要的! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2012-10-22
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多