Insert a view on a custom page or block | Drupal 8

Insert a view on a custom page or block

Submitted by editor on Fri, 02/10/2017 - 11:55
Question

How to add and render a views page or block in a custom page or block on drupal 8 ?

This tutorial show toy how to insert an existing views into a custom page or custom block.

 

Render a views block.

Example : Show Who's online block

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

  //$content = $view->buildRenderable('who_s_online_block');
  //$content = $view->buildRenderable('block', $args);

  $content = $view->buildRenderable();
  $output[] = $content;
}

Render a views page with selected exposed filter.

Example : Show People page with user name's contains 'admin' and has administrator role

$view = Views::getView('user_admin_people');
if (is_object($view)) {
  $view->setExposedInput([
    'role' => 'administrator',
    'user' => 'admin',
  ]);
  $view->setDisplay('page_1');
  $view->preExecute();
  $view->execute();

  //$content = $view->buildRenderable('page_1');
  $content = $view->buildRenderable();
  $output[] = $content;
}

 

Few other configurations:

$view->setArguments([]);
$view->setItemsPerPage(10);
$view->setOffset(5);
$view->setTitle("A new title");

Add new comment

Plain text

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