6

I am trying to inject the entity query service into a custom field widget. This is the relevant code:

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

The following error results:

Recoverable fatal error: Argument 6 passed to Drupal\custom_module\Plugin\Field\FieldWidget\AddressWidget::__construct() must be an instance of Drupal\Core\Entity\Query\QueryFactory, none given, called in /homedir/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line 130.

Is it not possible to use dependency injection in this case or am I missing something?

14

What you are missing is to implement \Drupal\Core\Plugin\ContainerFactoryPluginInterface, which defines the create() method.

See \Drupal\file\Plugin\Field\FieldWidget\FileWidget for an example.

  • Awesome! Just made my day. :) – Beau Apr 10 at 20:06

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.