2

I'm creating a few custom classes that extend FieldItemList and they need some services injected.

I've had a look at core classes that extend that class and none of them do dependency injection, they all call \Drupal::service().

Is there a way to inject services here or should I follow the core pattern?

3
  • No, there is still no way to inject services and you have to use the static service wrapper. See this comment and the linked issue drupal.stackexchange.com/questions/224247/…
    – 4uk4
    Commented Apr 5, 2022 at 16:35
  • Does this answer your question? How do I inject a dependency into a @FieldType plugin?
    – leymannx
    Commented Apr 5, 2022 at 16:52
  • FieldItemList isn't a field type plugin strictly speaking, but it sounds like the same thing applies. I'm going to wrap the services I need in my own service so I only have to call the service wrapper once.
    – Lambic
    Commented Apr 5, 2022 at 16:59

1 Answer 1

1

The field type plugin manager instantiates both, FieldItem and FieldItemList via the typed data manager:

Drupal\Core\Field\FieldTypePluginManager

  public function createFieldItemList(FieldableEntityInterface $entity, $field_name, $values = NULL) {
    // Leverage prototyping of the Typed Data API for fast instantiation.
    return $this->typedDataManager->getPropertyInstance($entity->getTypedData(), $field_name, $values);
  }

  public function createFieldItem(FieldItemListInterface $items, $index, $values = NULL) {
    // Leverage prototyping of the Typed Data API for fast instantiation.
    return $this->typedDataManager->getPropertyInstance($items, $index, $values);
  }

To be able to inject services you need to wait until this issue Allow typed data plugins to receive injected dependencies is resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.