Wednesday, May 22, 2013

How to rewrite a views field based on the value of a separate field.

Recently at work I was configuring a view of staff members.  Staff could be a Team Leader,  a Team Leader *and* a Board Member, or neither.  An integer list field, field_staff_leader, gave these options the value of 1, 2, and 0, respectively.  The view itself displayed team leaders, so obviously I added a simple filter that only displayed staff members that had a value of 1 or 2 in field_staff_leader.  Simple enough.  The tricky part was the value of another (text) field, field_role.  This field needed to be displayed normally if the value of field_staff_leader was 1 (is a Team Leader), but if the value was 2 (Team Leader and Board Member), field_role needed to be overwritten with the text "Board Member".

There's a hook for that! hook_views_pre_render does exactly what I needed.  Here's the code
/**

 * Check for Board Member status and overwrite field_role if TRUE .

 */

function mymodule_views_pre_render(&$view) {

  $results = &$view->result;

    foreach ($results as $key => $result) {

      if (($view->name == 'staff') && ($view->current_display == 'panel_pane_1')) {

        $field_board = $result->_field_data['nid']['entity']->field_staff_leader;

        if ($field_board['und'][0]['value'] == '2') {

          $results[$key]->field_field_role[0]['rendered']['#markup'] = 'Board Member';

      }

    }

  }
 
To break it down: First you need to access the view's results, and then of course make sure that you're applying your code to the correct view display.  If you are not sure what the view name or display id is, add dsm($view); to your code (be sure you have the devel module enabled), and your needed values will be in $view->name, and $view->current_display, respectively. 
/**

 * Check for Board Member status and overwrite field_role if TRUE .

 */

function mymodule_views_pre_render(&$view) {

  $results = &$view->result;

    foreach ($results as $key => $result) {

      if (($view->name == 'staff') && ($view->current_display == 'panel_pane_1')) {
Once you have targeted the correct view/display, check the field value:

        $field_board = $result->_field_data['nid']['entity']->field_staff_leader;

        if ($field_board['und'][0]['value'] == '2') {
...and then add your custom markup:
          $results[$key]->field_field_role[0]['rendered']['#markup'] = 'Board Member';
Then you may go enjoy your fully functional Death Star. Er, View.

No comments:

Post a Comment