9

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?

2
  • 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! Mar 23, 2017 at 10:13
  • 1
    Add an answer and set it as resolved
    – Eyal
    Mar 23, 2017 at 10:23

1 Answer 1

3

Make sure the entity id exists and the error disappears.

2
  • 2
    How do you ensure so? Mar 24, 2017 at 13:02
  • 1
    You can check if the entity object isset() or is not NULL, and use get() only if the condition passes. Aug 14, 2018 at 14:54

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