Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

3
  • 3
    My first instinct upon looking at this was "oh no, what about the dependency injection they keep hitting us over the head with in Drupal-land thesedays?", but - on inspection - the static ::load($id) method shared by all types of entities has all of the necessary dependency injection support built in - so this would now be my pick of how to load an entity of any kind (node, comment etc). In fact it beats me why anyone would use the long-hand \Drupal::entityTypeManager()->blah->blah->blah method now! (maybe someone else will chime in and give a good reason for that?) Commented Oct 4, 2018 at 0:23
  • 1
    @DanielScott – \Drupal::entityTypeManager()->getStorage('ENTITY_TYPE_ID')->load($id); is very easy to remember. You simply replace ENTITY_TYPE_ID and then you can load or loadMultiple or loadByProperties etc. And it works for nodes, for terms, for users, for roles, for vocabularies, for node types etc. You can even query the database from it. Commented Jun 10, 2020 at 10:43
  • 1
    @DanielScott, not the question or both answers are about dependency injection. This would look like $this->entityTypeManager->getStorage('ENTITY_TYPE_ID')->load($id);. But the long-hand static call makes refactoring easier if you need DI. Commented Jun 10, 2020 at 13:39