Skip to main content

Drupal 9: Dynamically modify the content displayed in the "empty" area of your view

This is how you can dynamically modify the content displayed in the "empty" area of your "custom" view when it's rendered as a block, based on the configuration's empty header text. Of course you can update the conditions as you think they fit better for you. You can put this into your web/modules/custom/custom.module file.

Although this is of course available from within views admin ui section, sometimes in production for example you might not provide for security reasons the views_ui module making it hard for modifying the empty header text message of a view.

/**
 * Implements hook_views_pre_render().
 */
function custom_views_pre_render(ViewExecutable $view) {
  // Get the display style of the view.
  $display_style = $view->getDisplay()->display['display_plugin'];

  if ($view->id() === 'custom_view_machine_name' &&
      $display_style === 'block' &&
      empty($view->result)) {

    $config = \Drupal::config('custom_module.settings');
    $empty_header_text = $config->get('views.custom.empty_text');

    if (isset($empty_header_text) && !empty(trim($empty_header_text))) {
      $view->display_handler->handlers['empty']['area']
        ->options['content']['value'] = t($empty_header_text);
    }
  }
}

 

views custom module php hook_views_pre_render