Drupal 8: Programmatically Adding a Views Footer

Recently, I needed to add some dynamic content to a Views footer. Specifically, I needed to change a link in the Views footer based on the current path, which isn’t an option from the Views UI. I found some good documentation showing how this can be done in older versions of Drupal (https://www.drupal.org/node/749452), but nothing for Drupal 8. I figured the approach must be similar in Drupal 8 so I started searching and reverse engineering.

First, I added a footer directly through the Views UI and exported my sites configuration using Drupal 8’s configuration management tools. Finding the footer in the exported YAML file provided some valuable insight on how I might add the footer programmatically.

Views Footer as found in the YAML export:

    id: area_text_custom
    table: views
    field: area_text_custom
    relationship: none
    group_type: group
    admin_label: ''
    empty: false
    tokenize: false
    content: Footer content is great
    plugin_id: text_custom

The YAML Views export provided the settings I needed to add the footer, but I also needed to figure out the right place to do it in code. If you are familiar with Views hooks, then you know there are a ton of them and sometimes finding the right one to use is a bit of trial and error. Since some of the Drupal 7 examples I found used function hook_views_pre_view(), I started with that hook. Using the Devel module, a great option for debugging in Drupal, and its dpm() function, I inspected the $view object. In Drupal 8, dpm() shows the available methods for an object. With a little bit of guesswork, the setHandler method seemed like the correct choice.

Output from the dpm() function. *Output from the dpm() function.*

I was able to add a Views footer with some code in a custom module:

use Drupal\views\ViewExecutable;
function YOURMODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_machine_name' && $display_id === 'view_display') {
    $options = array(
      'id' => 'area_text_custom',
      'table' => 'views',
      'field' => 'area_text_custom',
      'relationship' => 'none',
      'group_type' => 'none',
      'admin_label' => '',
      'empty' => TRUE,
      'tokenize' => FALSE,
      'content' => ‘Footer content is great.,
      'plugin_id' => 'text_custom',
    $view->setHandler('view_display', 'footer', 'area_text_custom', $options);

One piece of the Drupal 8 Views module has been solved!

Code Drupal 8 Drupal Drupal Planet