Render a Node or an Entity | Drupal 8

Render a Node or an Entity

Submitted by editor on Wed, 09/13/2017 - 09:59
Question

How to render nodes or entities programmatically on drupal 8, like node_view() on drupal 7 ?
How to show a node or an entity using a display mode programmatically ?

On drupal 8 every elements (almost) are an entity, as any entity you can render a node.

Display a node

$entity_type = 'node';
$entity_id = '1';
$view_mode = 'full';
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
$pre_render = $view_builder->view($entity, $view_mode);
$build[] = $pre_render;
// OR to get HTML
//$html = render($pre_render);

//Note : you can also use if you don't want to use different entity types.
$node = Node::load($nid);

Display a view

$view = Views::getView('who_s_online');
if (is_object($view)) {
  $view->setDisplay('who_s_online_block');
  $view->preExecute();
  $view->execute();
  $output = $view->buildRenderable();
}

 

Render a node field

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$storage = \Drupal::entityTypeManager()->getStorage('node');
$nid = 1;
$node = $storage->load($nid);
$view = $view_builder->viewField($node->get('body'), [
'type' => 'string', // string, entity_reference_label
'label' => 'hidden',
'settings' => ['link' => FALSE],
]);
$output = render($view);

Note : If you want to just get a value, you cal also do like this.
$value= Node::load($nid)->get('body')->value;

Comments

Anonymous (not verified)

Mon, 05/21/2018 - 19:47

\Drupal\Core\Database\Database::setActiveConnection('external');

    // Get a connection going
    $db = \Drupal\Core\Database\Database::getConnection();

    $query = $db->select('node', 'n');
    $result = $query
              ->fields('n')
              ->condition('n.type', 'article')
              ->execute()
              ->fetchAll();

    $storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $storage->load($result[0]->nid);

    dump($node);

    // Switch back
    \Drupal\Core\Database\Database::setActiveConnection();

$node = $storage->load($result[0]->nid); // this load a node from default DB and not external DB so that's not good

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.