Skip to main content
views alter

Altering views table output

Views module provides an easy way to render data from the Drupal database. It is often needed to use table output format to meet the design requirements. One such similar occasion needed customizing the table output.

The scenario was, we had a list of discounts with validity date as its one of the attributes. We wanted to show expired discounts in a different color to distinguish it from active discounts. What helped us was hook_preprocess_views_view_table().

[[{"type":"media","view_mode":"media_original","fid":"110","attributes":{"alt":"","class":"media-image","style":"width: 600px; height: 421px; ","typeof":"foaf:Image"}}]]

The row_classes adds the beauty here. The view maintains a separate array of css classes respective to the table's row index.

i.e. $vars['rows'][0] will be applied css class from $vars['row_classes'][0]. I hope I was clear enough. The code we used looks as below. 

  1. function HOOK_preprocess_views_view_table(&$vars) {
  2.   if(in_array($vars['view']->name,array('VIEWS_1','VIEWS_2'))) {
  3.     foreach ($vars['rows'] as $k => $row ) {
  4.       $validity = $row['field_validity'];
  5.       if (_CHECK_VALIDITY($validity)) {
  6.         $vars['row_classes'][$k][] = 'my-expired-css-class';
  7.       }
  8.     }
  9.   }

I looped through each row and checked the validity of the date, if in case of  expiration, I added my custom css class my-expired-css-class which can override the default color. Reference: template_preprocess_views_view_table()