10

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?

1 Answer 1

21

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.

1
  • Awesome! Just made my day. :) Commented Apr 10, 2019 at 20:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.