Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Insert a view on a custom page or block

By editor , 10 February, 2017
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");

Tags

  • Drupal 8
  • Code
  • Views
Create a simple module for Drupal 8 - Step 2 - Create Simple Page
Create a simple module for Drupal 8 - Step 3 - Create Dynamic Page/ Block
Render a Node or an Entity

Comments

Plain text

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

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer