3

I created a custom entity (submenu) in Drupal 8. I need to render this custom entity in my custom module. Thi 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?

closed as too broad by kiamlaluno Oct 15 '17 at 9:17

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
1

Make sure the entity id exists and the error disappears.

  • 1
    How do you ensure so? – Pierre.Vriens Mar 24 '17 at 13:02
  • 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.