You are here

views_fields_on_off.module in Views Fields On/Off 7

Same filename and directory in other branches
  1. 8 views_fields_on_off.module

Provides a Views Global field that allows users to turn fields on/off.

File

views_fields_on_off.module
View source
<?php

/**
 * @file
 * Provides a Views Global field that allows users to turn fields on/off.
 */

/**
 * Implements hook_views_api().
 */
function views_fields_on_off_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'views_fields_on_off') . '/includes/views',
  );
}

/**
 * Implements hook_views_pre_view().
 */
function views_fields_on_off_views_pre_view(&$view, &$display_id, &$args) {
  $use_display_id = $display_id;
  if ($display_id != 'default' && array_key_exists('fields', $view->display['default']->handler->options) && !count($view->display[$display_id]->handler->options['fields'])) {

    // This display has no fields, but the default does, so this view is not
    // overridden.
    // This means we have to alter the default display. Altering the actual
    // $display_id display won't work.
    $use_display_id = 'default';
  }

  // Now that we know what our display ID is, we can see whether or not that
  // display has the On/Off handler on it.
  if (array_key_exists('fields', $view->display[$use_display_id]->handler->options) && array_key_exists('views_fields_on_off_form', $view->display[$use_display_id]->handler->options['fields'])) {

    // Grab the fields_on_off values that have been submitted already.
    $params = drupal_get_query_parameters();
    $on_off_submitted = array_key_exists('fields_on_off_hidden_submitted', $params);
    $checked_fields = array_key_exists('fields_on_off', $params) ? $params['fields_on_off'] : array();

    // We need $on_off_submitted because if the form is submitted with no
    // checkboxes checked, none of the fields_on_off values will be present,
    // so it thinks this is a fresh view and all the columns should be checked.
    $hideable_fields = $view->display[$use_display_id]->handler->options['fields']['views_fields_on_off_form']['fields'];

    // Here if there are no checked fields but the form has been submitted,
    // we want to turn off the field.
    if (count($checked_fields) || $on_off_submitted) {
      foreach ($view->display[$use_display_id]->handler->options['fields'] as $key => $field) {
        if (!array_key_exists($key, $checked_fields) && array_key_exists($key, $hideable_fields) && $hideable_fields[$key]) {

          // If there are fields specified, and this field is one of them,
          // hide it!
          $view->display[$use_display_id]->handler->options['fields'][$key]['exclude'] = 1;
        }
      }
    }

    // And always hide the on/off field or it'll just show up empty.
    $view->display[$use_display_id]->handler->options['fields']['views_fields_on_off_form']['exclude'] = 1;
  }
}