Skip to main content

Drupal 8 and blocks in views header

Strange but true: In drupal 8 you can place a rendered block entity into the views header - but only, if this block shows up anywhere, if it is placed in a region. I've read, that display settings of the block are respected in this case.

Now, I needed the block only in the views header of a special view - I didn't want to define a hidden region or anything the like.

My solution was to create a custom views area field and render the block this way. Only two files where needed in my drupal module:

roomprices.views.inc
src/Plugin/views/area/RoompricesSeasons.php

And for sure, I had to create a block in my custom module. The usecase is a table of season times in the header of a view showing all hotel rooms with their prices in different seasons. I didn't want to repeat the seasons times on every node, at least not in desktop views of the page.

In roomprices.views.inc I've put:

<?php

/**
 * Implements hook_views_data().
 */
function roomprices_views_data() {
  $data['views']['roomprices_seasons'] = array(
    'title' => t('Seasons'),
    'help' => t('Table of season times'),
    'area' => array(
      'id' => 'roomprices_seasons',
    ),
  );
  return $data;
}

in RoompricesSeasons.php:

<?php

namespace Drupal\roomprices\Plugin\views\area;

use Drupal\views\Plugin\views\area\AreaPluginBase;
use Drupal\roomprices\Plugin\Block\SeasonsBlock;

/**
 * Defines a views area plugin.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("roomprices_seasons")
 */
class RoompricesSeasons extends AreaPluginBase {

  /**
   * {@inheritdoc}
   */
  public function render($empty = FALSE) {
        $seasons = SeasonsBlock::build();
        return $seasons;
  }
}