2

How do I add view header content in code?

I have seen questions related to this but only where the view is being embedded. I am not embedding any view, but would like to provide content for the view headers in code as I have quite a few views, and I do not want to add the content through the views UI as it is difficult to make changes quickly and as some views have many pages and share the same header.

Currently I have this code.

function MYMODULE_preprocess_views_view(&$vars){
  $function = __FUNCTION__ . '_' . $vars['name'];
  if (function_exists($function)) {
    $function($vars);
  }
}

function MYMODULE_preprocess_views_view_VIEW_NAME(&$vars){
  // do something here.
  $vars['attachment_before'] .= $SOME_CONTENT;
}
2
  • drupal.stackexchange.com/questions/49160/… Commented Aug 22, 2014 at 12:42
  • I saw that. However, I am not embedding the view in code, and in that answer the header is added to the view before it is run. I want to hook into a few views and add the header. The header does not need to run through views. I just want to append contextual html markup through a few conditional statements. So how and where is the best place to hook into the view? Commented Aug 22, 2014 at 14:12

1 Answer 1

6

Use hook_views_pre_render().

/**
 * Implements hook_views_pre_render().
 */
function cv_views_pre_render(&$view) {
  // dpm($view); // dpm view here to see its properties.
  // and replace $view->name and $view->current_display with actual values from your view.
  // Note that my example uses Global: Text area for header, that's why I use $view->header['area']. 
  // Other options available for header have different names. Try to find one that you use.
  if ($view->name == 'homepage' && $view->current_display = 'homepage_page_display') {
    $view->header['area']->options['content'] = t('TEST message');
  }
}
3
  • 1
    Thanks. I read in the documentation for hook_view_pre_render: Adding output to the view can be accomplished by placing text on $view->attachment_before and $view->attachment_after. Altering the content can be achieved by editing the items of $view->result. It is exactly what I needed. Commented Aug 22, 2014 at 14:34
  • 1
    I used $view->attachment_before also in similar case. Perfect !
    – Kojo
    Commented Aug 5, 2015 at 14:05
  • attachment_before show before the view, but below the exposed form. the header[area] in the example shows above the exposed form.
    – commonpike
    Commented Jul 10, 2023 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.