Score:-3

Update entityManager()->getViewBuilder from 5 year old site?

sy flag

I have a Drupal 8 module which hasn't been updated for 5 years. I m trying to update to current version of Drupal.

The error I get is

Error: Call to undefined method Drupal::entityManager()

The code causing the error is below.

      $viewbuilder = \Drupal::entityManager()->getViewBuilder('paragraph');
      $data = $viewbuilder->view($paragraph);
      $array['#cache']['tags'][] = 'node:' . $node->id();

When I search one suggestions is to load through drupal service like below

\Drupal::service('entity_field.manager')->getViewBuilder('paragraph');

This gives a similar error, as does using EntityTypeManager

\Drupal::EntityTypeManager()->getViewBuilder('paragraph');

How do I update this code?

Thanks for any help

apaderno avatar
us flag
Welcome to Drupal Answers! From the question, I understand that every time you call a `\Drupal` method, you get an error saying that method does not exist. Is that correct? Otherwise, what you do you mean with *a similar error*?
Score:3
de flag

View builders are now retrieved from the service entity_type.manager, which can be retrieved globally using \Drupal::entityTypeManager():

\Drupal::service('entity_type.manager')->getViewBuilder('paragraph');

Or:

\Drupal::entityTypeManager()->getViewBuilder('paragraph');
Score:1
us flag

In Drupal 10, the code to get an entity view builder is used, for example, in BlockViewBuilderTest::testBasicRendering().

$builder = \Drupal::entityTypeManager()->getViewBuilder('block');
$output = $builder->view($entity, 'block');

The same code is used in Drupal 9 and Drupal 8.9.

Older code used Drupal::entityManager(), but as the documentation page says, that method has been deprecated and removed in Drupal 9. \Drupal::entityTypeManager() should be instead used in most cases.

If you get an error about \Drupal::entityTypeManager() being a non existing method, then the core/lib/Drupal.php file is probably corrupted.

The entity_field.manager is a completely different service and it is not the service you need to use. The class implementing it (EntityFieldManager) does not define any getViewBuilder() method.

I sit in a Tesla and translated this thread with Ai:

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.