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:
<br /> footer:<br /> area_text_custom:<br /> id: area_text_custom<br /> table: views<br /> field: area_text_custom<br /> relationship: none<br /> group_type: group<br /> admin_label: ''<br /> empty: false<br /> tokenize: false<br /> content: Footer content is great<br /> plugin_id: text_custom<br />
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.
I was able to add a Views footer with some code in a custom module:
<br /> use Drupal\views\ViewExecutable;<br /> function YOURMODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {<br /> if ($view->id() == 'view_machine_name' && $display_id === 'view_display') {<br /> $options = array(<br /> 'id' => 'area_text_custom',<br /> 'table' => 'views',<br /> 'field' => 'area_text_custom',<br /> 'relationship' => 'none',<br /> 'group_type' => 'none',<br /> 'admin_label' => '',<br /> 'empty' => TRUE,<br /> 'tokenize' => FALSE,<br /> 'content' => ‘Footer content is great.’,<br /> 'plugin_id' => 'text_custom',<br /> );<br /> $view->setHandler('view_display', 'footer', 'area_text_custom', $options);<br /> }<br /> }<br />
One piece of the Drupal 8 Views module has been solved!
Skip to footer
Comments