Score:0

How can I inject services into my entity bundle class?

cn flag

I have an entity with a JSON field, and I do some complicated processing when the entity is saved.

Right now, I do this processing in hook_ENTITY_presave(), which calls a service I have created in a custom module.

However, since Drupal 9.3, we can create bundle classes to extend entities cleanly.

So I made one for my entity, and I wrote some new getters and setters so I can do $entity->getMyValue() instead of $entity->field_abc->value.

Now, I want to take the next step and inject my service into the entity and move the processing directly into the entity on save. How can I do that?

Score:0
cn flag

Alas, this is not yet possible. There is a discussion in the Core issue queue on how to proceed with this.

As noted in the discussion linked above, an alternative to do this now is to use the Typed Entity module, which wraps entities into objects and allows you to do dependency injection.

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.