I created a custom entity (submenu) in Drupal 8. I need to render this custom entity in my custom module. This is the code I am using.

$entity_type = 'submenu';
$entity_id = '1'; // static for example purpose
$view_mode = 'full';         

$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('submenu');
$pre_render = $view_builder->view($entity, $view_mode);
$render_output = render($pre_render);

I keep getting the following error.

TypeError: Argument 1 passed to Drupal\Core\Entity\EntityViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given

Why do I get this error?

  • My code appeared to be correct. Because I dynamically loaded the $entity_id variable I got the error when this variable was empty. Problem solved! – Stef Van Looveren Mar 23 '17 at 10:13
  • 1
    Add an answer and set it as resolved – Eyal Mar 23 '17 at 10:23

Make sure the entity id exists and the error disappears.

  • 2
    How do you ensure so? – Pierre.Vriens Mar 24 '17 at 13:02
  • 1
    You can check if the entity object isset() or is not NULL, and use get() only if the condition passes. – Stef Van Looveren Aug 14 '18 at 14:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.