I recently had a requirement to have different 'no results' text display under different circumstances on a Drupal 8 site I was working on. It was much simpler than I thought and I'll share the text snippet I used.

/**
 * Implements hook_views_pre_view().
 */
function my_module_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'james_davidson_view' && $display_id === 'page') {
    $message = t("I'm sorry there are no results for that search criteria.");

    $item = array(
      'id' => 'area',
      'table' => 'views',
      'field' => 'area',
      'relationship' => 'none',
      'group_type' => 'group',
      'admin_label' => '',
      'empty' => TRUE,
      'tokenize' => FALSE,
      'content' => array(
        'value' => $message,
        'format' => "full_html",
      ),
      'plugin_id' => 'text',
    );

    $view->setHandler('page', 'empty', 'area', $item);
  }
}

Adding "area's" in Drupal 8 views feels much than previously in Drupal 7. In this instance I'm mocking up an 'empty' area, of type 'text', and populating it with a string. In this instance it's hardcoded, but this would be an opportunity to generate different markup depending on whatever you wanted.

Add new comment