自定义字段小部件中的依赖项注入


9

我正在尝试将实体查询服务注入到自定义字段小部件中。这是相关代码:

/**
 * Plugin implementation of the 'address_options' widget.
 *
 * @FieldWidget(
 *   id = "address_options",
 *   label = @Translation("Addresses"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class MyCustomWidget extends WidgetBase {

  /**
   * The entity query factory service.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQuery;

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, QueryFactory $entity_query) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityQuery = $entity_query;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity.query')
    );
  }

出现以下错误:

可恢复的致命错误:传递给Drupal \ custom_module \ Plugin \ Field \ FieldWidget \ AddressWidget :: __ construct()的参数6必须是Drupal \ Core \ Entity \ Query \ QueryFactory的实例,未提供,在/ homedir / core / lib中调用/Drupal/Core/Field/WidgetPluginManager.php行130。

在这种情况下是否无法使用依赖项注入,或者我缺少什么?

Answers:


17

您缺少的是实现\ Drupal \ Core \ Plugin \ ContainerFactoryPluginInterface,它定义了create()方法。

有关示例,请参见\ Drupal \ file \ Plugin \ Field \ FieldWidget \ FileWidget。


太棒了!刚刚度过了我的一天。:)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.