How to render a custom entity in a controller? I created a custom entity called foo. This entity has a unique name field as well as the standard id key. I would like to build a page where the user can see the entity rendered similarly to how it would be on the admin page, but instead of referencing it by the id, I would like to use the name.

I have the following in my controller:

public function content($name) {
  $output = [];
  //Add a couple things to the $output array
  $output['first thing'] = [/*stuff*/];

  $sql = "SELECT id FROM foo WHERE name=:name";
  $sql_params = [':name' =&gt; $name];
  $results = db_query($sql, $sql_params)-&gt;fetchAll(PDO::FETCH_ASSOC);
  $render_array = [];
  if (count($results) &gt; 0) {
    $id = $results[0]['id'];

    $entity_type = 'foo';
    $view_builder = \Drupal::entityTypeManager()-&gt;getViewBuilder($entity_type);
    $controller = \Drupal::entityManager()-&gt;getStorage($entity_type);
    $entity = $controller-&gt;load($id);
    $build = $view_builder-&gt;view($entity);
    $render_array = render($build);
    $output['entity'] = $render_array;
  }
  return $output;
}


However, I receive an error: User error: "entity" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).

What do I need to do differently to make my entity render to the page?
Controllers should return a render array (or a custom response), you almost never need to render anything yourself outside a template.

Just replace this:

$build = $view_builder-&gt;view($entity);
$render_array = render($build);
$output['entity'] = $render_array;


with:

$output = $view_builder-&gt;view($entity);


to return a render array and let Twig handle the rendering.

But going further, you don't need to (and shouldn't) go into the database directly for this; the entity type manager works for all entity types, including your own, and entity storage classes have methods to help with this. 

(As an aside, that service should also be injected rather than loaded from the static Drupal class method, your controller class is container aware). 

Once that's available the code would be simplified to something like this:

public function content($name) {
  $build = [];
  $entity_type = 'foo';

  $storage = $this-&gt;entityTypeManager-&gt;getStorage($entity_type);
  $entities = $storage-&gt;loadByProperties(['name' =&gt; $name]);

  if ($entity = reset($entities)) {
    $build = $this-&gt;entityTypeManager-&gt;getViewBuilder($entity_type)-&gt;view($entity);
  }

  return $build;
}


To go one step further, you can add a loadByName() method to your entity class with a slight variation of the above, might save you some time and repetition further down the line.