-3

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

1
  • 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?
    – apaderno
    Commented Apr 20, 2023 at 9:32

2 Answers 2

3

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');
1

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.

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.