Score:2

Dependency injection in FieldItemList

ph flag

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?

4uk4 avatar
cn flag
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 https://drupal.stackexchange.com/questions/224247/how-do-i-inject-a-dependency-into-a-fieldtype-plugin/224248#comment273484_224248
leymannx avatar
ne flag
Does this answer your question? [How do I inject a dependency into a @FieldType plugin?](https://drupal.stackexchange.com/questions/224247/how-do-i-inject-a-dependency-into-a-fieldtype-plugin)
Lambic avatar
ph flag
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.
Score:1
cn flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.