You are here

better_exposed_filters.theme in Better Exposed Filters 7

File

better_exposed_filters.theme
View source
<?php

/**
 * Themes a select element as a collection of checkboxes enclosed in a collapsible fieldset
 *
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 *                      Properties used: title, value, options, description
 * @return HTML string representing the form element.
 */
function theme_select_as_checkboxes_fieldset($vars) {

  // Merge incoming element with some default values. Prevents a lot of
  //    $foo = isset($bar) ? $bar : $bar_default;
  $element = array_merge(array(
    '#bef_title' => '',
    '#bef_description' => '',
  ), $vars['element']);
  $fieldset = array(
    '#title' => $element['#bef_title'],
    '#description' => $element['#bef_description'],
    '#attributes' => array(
      'class' => array(
        'bef-select-as-checkboxes-fieldset',
        'collapsible',
      ),
    ),
  );
  if (empty($element['#value'])) {

    // Using the FAPI #collapsible and #collapsed attribute doesn't work here
    // TODO: not sure why...
    $fieldset['#attributes']['class'][] = 'collapsed';
  }

  // Description is rendered as part of the fieldset, don't render it twice.
  unset($element['#description']);
  $fieldset['#children'] = theme('select_as_checkboxes', array(
    'element' => $element,
  ));
  return theme('fieldset', array(
    'element' => $fieldset,
  ));
}

/**
 * Themes a select element as a set of checkboxes
 *
 * @see theme_select(), http://api.drupal.org/api/function/theme_select/6
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 *                      Properties used: title, value, options, description
 * @return HTML string representing the form element.
 */
function theme_select_as_checkboxes($vars) {
  $element = $vars['element'];
  if (!empty($element['#bef_nested'])) {
    if (empty($element['#attributes']['class'])) {
      $element['#attributes']['class'] = array();
    }
    $element['#attributes']['class'][] = 'form-checkboxes';
    return theme('select_as_tree', array(
      'element' => $element,
    ));
  }

  // the selected keys from #options
  $selected_options = empty($element['#value']) ? $element['#default_value'] : $element['#value'];

  // Grab exposed filter description.  We'll put it under the label where it makes more sense.
  $description = '';
  if (!empty($element['#description'])) {
    $description = '<div class="description">' . $element['#description'] . '</div>';
    unset($element['#description']);
  }
  $output = '<div class="bef-checkboxes">';
  foreach ($element['#options'] as $option => $elem) {
    if ('All' === $option) {

      // TODO: 'All' text is customizable in Views
      // No need for an 'All' option -- either unchecking or checking all the checkboxes is equivalent
      continue;
    }

    // Check for Taxonomy-based filters
    if (is_object($elem)) {
      list($option, $elem) = each(array_slice($elem->option, 0, 1, TRUE));
    }

    /*
     * Check for optgroups.  Put subelements in the $element_set array and add a group heading.
     * Otherwise, just add the element to the set
     */
    $element_set = array();
    $is_optgroup = FALSE;
    if (is_array($elem)) {
      $output .= '<div class="bef-group">';
      $output .= '<div class="bef-group-heading">' . $option . '</div>';
      $output .= '<div class="bef-group-items">';
      $element_set = $elem;
      $is_optgroup = TRUE;
    }
    else {
      $element_set[$option] = $elem;
    }
    foreach ($element_set as $key => $value) {
      $output .= bef_checkbox($element, $key, $value, array_search($key, $selected_options) !== FALSE);
    }
    if ($is_optgroup) {
      $output .= '</div></div>';

      // Close group and item <div>s
    }
  }
  $output .= '</div>';

  // Fake theme_checkboxes() which we can't call because it calls theme_form_element() for each option
  $attributes['class'] = array(
    'form-checkboxes',
    'bef-select-as-checkboxes',
  );
  if (!empty($element['#bef_select_all_none'])) {
    $attributes['class'][] = 'bef-select-all-none';
  }
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = array_merge($element['#attributes']['class'], $attributes['class']);
  }
  return '<div' . drupal_attributes($attributes) . ">{$description}{$output}</div>";
}

/**
 * Themes a select element as a series of hidden fields
 *
 * @see theme_select(), http://api.drupal.org/api/function/theme_select/6
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 *                      Properties used: title, value, options, description
 * @return HTML string representing the form element.
 */
function theme_select_as_hidden($vars) {
  $element = $vars['element'];
  $output = '';
  $selected_options = empty($element['#value']) ? $element['#default_value'] : $element['#value'];
  $properties = array(
    'title' => $element['#title'],
    'description' => $element['#description'],
    'required' => FALSE,
  );
  foreach ($element['#options'] as $option => $elem) {

    // Check for Taxonomy-based filters
    if (is_object($elem)) {
      list($option, $elem) = each(array_slice($elem->option, 0, 1, TRUE));
    }

    /*
     * Check for optgroups.  Put subelements in the $element_set array and add a group heading.
     * Otherwise, just add the element to the set
     */
    $element_set = array();
    if (is_array($elem)) {
      $element_set = $elem;
    }
    else {
      $element_set[$option] = $elem;
    }
    foreach ($element_set as $key => $value) {

      // Only render fields for selected values -- no selected values renders zero fields
      if (array_search($key, $selected_options) !== FALSE) {

        // Custom ID for each hidden field based on the <select>'s original ID
        $id = drupal_html_id($element['#id'] . '-' . $key);

        // Very similar to theme_hidden (http://api.drupal.org/api/function/theme_hidden/6)
        $hidden = '<input type="hidden" ' . 'name="' . $element['#name'] . '[]" ' . 'id="' . $id . '" ' . 'value="' . check_plain($key) . '" ' . drupal_attributes($element['#attributes']) . ' />';
        $output .= theme('form_element', array(
          'element' => array_merge($properties, array(
            '#id' => $id,
            '#children' => $hidden,
          )),
        ));
      }
    }
  }
  return $output;
}

/**
 * Themes a select element as a collection of radio buttons enclosed in a collapsible fieldset
 *
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 *                      Properties used: title, value, options, description
 * @return HTML string representing the form element.
 */
function theme_select_as_radios_fieldset($vars) {

  // Merge incoming element with some default values. Prevents a lot of
  //    $foo = isset($bar) ? $bar : $bar_default;
  $element = array_merge(array(
    '#bef_title' => '',
    '#bef_description' => '',
  ), $vars['element']);

  // The "all" option is the first in the list. If the selected radio button is the all
  // option, then leave the fieldset collapsed.  Otherwise, render it opened.
  $all = array_shift(array_keys($element['#options']));
  $fieldset = array(
    '#title' => $element['#bef_title'],
    '#description' => $element['#bef_description'],
    '#attributes' => array(
      'class' => array(
        'bef-select-as-checkboxes-fieldset',
        'collapsible',
      ),
    ),
  );
  if (empty($element['#value'])) {

    // Using the FAPI #collapsible and #collapsed attribute doesn't work here
    // TODO: not sure why...
    $fieldset['#attributes']['class'][] = 'collapsed';
  }
  $fieldset['#children'] = theme('select_as_radios', $element);
  return theme('fieldset', array(
    'element' => $fieldset,
  ));
}

/**
 * Themes a select drop-down as a collection of radio buttons
 *
 * @see theme_select(), http://api.drupal.org/api/function/theme_select/7
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 *                      Properties used: return_value, value, attributes, title, description
 * @return HTML string representing the form element.
 */
function theme_select_as_radios($vars) {
  $element =& $vars['element'];
  if (!empty($element['#bef_nested'])) {
    return theme('select_as_tree', $vars);
  }
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = array(
    'bef-select-as-radios form-radios',
  );
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  }
  $output = '';
  foreach (element_children($element) as $key) {
    $element[$key]['#default_value'] = NULL;
    $element[$key]['#children'] = theme('radio', array(
      'element' => $element[$key],
    ));
    $output .= theme('form_element', array(
      'element' => $element[$key],
    ));
  }
  return '<div' . drupal_attributes($attributes) . '>' . $output . '</div>';
}

/**
 * Themes a taxonomy-based exposed filter select element as a nested unordered list.  Note: this
 * routine depends on the '-' char prefixed on the term names by Views to determine depth.
 *
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 * @return HTML
 */
function theme_select_as_tree($vars) {
  $element = $vars['element'];

  // The selected keys from #options
  $selected_options = empty($element['#value']) ? $element['#default_value'] : $element['#value'];

  /*
   *  Build a bunch of nested unordered lists to represent the hierarchy based on the '-' prefix
   *  added by Views or optgroup structure.
   */
  $output = '<ul class="bef-tree">';
  $curr_depth = 0;
  foreach ($element['#options'] as $option_value => $option_label) {

    // Check for Taxonomy-based filters
    if (is_object($option_label)) {
      list($option_value, $option_label) = each(array_slice($option_label->option, 0, 1, TRUE));
    }

    // Check for optgroups -- which is basically a two-level deep tree
    if (is_array($option_label)) {

      // TODO:
    }
    else {

      // Build hierarchy based on prefixed '-' on the element label
      preg_match('/^(-*).*$/', $option_label, $matches);
      $depth = strlen($matches[1]);

      // Build either checkboxes or radio buttons, depending on Views' settings
      $html = '';
      if (!empty($element['#multiple'])) {
        $html = bef_checkbox($element, $option_value, ltrim($option_label, '-'), array_search($option_value, $selected_options) !== FALSE);
      }
      else {
        $html = theme('radio', array(
          'element' => $element[$option_value],
        ));
      }
      if ($depth > $curr_depth) {

        // We've moved down a level: create a new nested <ul>
        // TODO: Is there is a way to jump more than one level deeper at a time?  I don't think so...
        $output .= "<ul class='bef-tree-child bef-tree-depth-{$depth}'><li>{$html}";
        $curr_depth = $depth;
      }
      elseif ($depth < $curr_depth) {

        // We've moved up a level: finish previous <ul> and <li> tags, once for each level, since we
        // can jump multiple levels up at a time.
        while ($depth < $curr_depth) {
          $output .= '</li></ul>';
          $curr_depth--;
        }
        $output .= "</li><li>{$html}";
      }
      else {

        // Remain at same level as previous entry. No </li> needed if we're at the top level
        if (0 == $curr_depth) {
          $output .= "<li>{$html}";
        }
        else {
          $output .= "</li><li>{$html}";
        }
      }
    }
  }

  // foreach ($element['#options'] as $option_value => $option_label)
  if (!$curr_depth) {

    // Close last <li> tag
    $output .= '</li>';
  }
  else {

    // Finish closing <ul> and <li> tags
    while ($curr_depth) {
      $curr_depth--;
      $output .= '</li></ul></li>';
    }
  }

  // Close the opening <ul class="bef-tree"> tag
  $output .= '</ul>';

  // Add exposed filter description
  $description = '';
  if (!empty($element['#description'])) {
    $description = '<div class="description">' . $element['#description'] . '</div>';
  }

  // Add the select all/none option, if needed
  if (!empty($element['#bef_select_all_none'])) {
    if (empty($element['#attributes']['class'])) {
      $element['#attributes']['class'] = array();
    }
    $element['#attributes']['class'][] = 'bef-select-all-none';
  }
  return '<div' . drupal_attributes($element['#attributes']) . ">{$description}{$output}</div>";
}

/**
 * Themes a select drop-down as a collection of links
 *
 * @see theme_select(), http://api.drupal.org/api/function/theme_select/6
 * @param array $vars - An array of arrays, the 'element' item holds the properties of the element.
 *                      Properties used: title, value, options, description, name
 * @return HTML string representing the form element.
 */
function theme_select_as_links($vars) {
  $element = $vars['element'];
  $output = '';
  $name = $element['#name'];

  // Collect selected values so we can properly style the links later
  $selected_options = array();
  if (empty($element['#value'])) {
    if (!empty($element['#default_values'])) {
      $selected_options[] = $element['#default_values'];
    }
  }
  else {
    $selected_options[] = $element['#value'];
  }

  // Add to the selected options specified by Views whatever options are in the
  // URL query string, but only for this filter
  $urllist = parse_url(request_uri());
  if (isset($urllist['query'])) {
    $query = array();
    parse_str(urldecode($urllist['query']), $query);
    foreach ($query as $key => $value) {
      if ($key != $name) {
        continue;
      }
      if (is_array($value)) {

        // This filter allows multiple selections, so put each one on the selected_options array
        foreach ($value as $option) {
          $selected_options[] = $option;
        }
      }
      else {
        $selected_options[] = $value;
      }
    }
  }

  // Go through each filter option and build the appropriate link or plain text
  foreach ($element['#options'] as $option => $elem) {

    // Check for Taxonomy-based filters
    if (is_object($elem)) {
      list($option, $elem) = each(array_slice($elem->option, 0, 1, TRUE));
    }

    /*
     * Check for optgroups.  Put subelements in the $element_set array and add a group heading.
     * Otherwise, just add the element to the set
     */
    $element_set = array();
    if (is_array($elem)) {
      $element_set = $elem;
    }
    else {
      $element_set[$option] = $elem;
    }
    $links = array();
    $multiple = !empty($element['#multiple']);
    foreach ($element_set as $key => $value) {

      // Custom ID for each link based on the <select>'s original ID
      $id = drupal_html_id($element['#id'] . '-' . $key);
      if (array_search($key, $selected_options) === FALSE) {
        $link = l($value, bef_replace_query_string_arg($name, $key, $multiple));
        $output .= theme('form_element', array(
          'element' => array(
            '#id' => $id,
            '#children' => $link,
          ),
        ));
      }
      else {

        // Selected value is output without a link
        // TODO: add link to remove this option from the filter?
        $elem = array(
          '#id' => $id,
          '#children' => $value,
        );
        _form_set_class($elem, array(
          'bef-select-as-links-selected',
        ));
        $output .= theme('form_element', array(
          'element' => $elem,
        ));
      }
    }
  }
  $properties = array(
    '#description' => isset($element['#description']) ? $element['#description'] : '',
    '#children' => $output,
  );
  return '<div class="bef-select-as-links">' . theme('form_element', array(
    'element' => $properties,
  )) . '</div>';
}

/*
 * Helper functions
 */

/**
 * Build a BEF checkbox -- very similar to theme_checkbox
 * (http://api.drupal.org/api/function/theme_checkbox/6)
 *
 * @param $element - array: original <select> element generated by Views
 * @param $value - string: value of this checkbox option
 * @param $label - string: label for this checkbox option
 * @param $selected - bool: checked or not
 * @return string: checkbox HTML
 */
function bef_checkbox($element, $value, $label, $selected) {
  $value = check_plain($value);
  $label = check_plain($label);
  $id = drupal_html_id($element['#id'] . '-' . $value);

  // Custom ID for each checkbox based on the <select>'s original ID
  $properties = array(
    '#required' => FALSE,
    '#id' => $id,
  );

  // Prevent the select-all-none class from cascading to all checkboxes
  if (!empty($element['#attributes']['class']) && FALSE !== ($key = array_search('bef-select-all-none', $element['#attributes']['class']))) {
    unset($element['#attributes']['class'][$key]);
  }
  $checkbox = '<input type="checkbox" ' . 'name="' . $element['#name'] . '[]" ' . 'id="' . $id . '" ' . 'value="' . $value . '" ' . ($selected ? 'checked="checked" ' : '') . drupal_attributes($element['#attributes']) . ' />';
  $properties['#children'] = "{$checkbox} <label class='option' for='{$id}'>{$label}</label>";
  $output = theme('form_element', array(
    'element' => $properties,
  ));
  return $output;
}

/**
 * Replaces/adds a given query string argument to the current URL
 *
 * @param string $key query string key (argument)
 * @param string $value query string value
 * @param bool $multiple TRUE if this key/value pair allows multiple values
 */
function bef_replace_query_string_arg($key, $value, $multiple = FALSE) {
  $path = arg();

  // Prevents us from having to check for each index from parse_url that we may use
  $urllist = array(
    'path' => '',
    'fragment' => '',
    'query' => '',
  );
  $urllist = array_merge($urllist, parse_url(request_uri()));
  $fragment = urldecode($urllist['fragment']);
  $query = array();
  parse_str(urldecode($urllist['query']), $query);
  if (isset($query[$key]) && is_array($query[$key])) {

    // multiple values allowed for this existing key
    $query[$key][] = $value;
  }
  else {

    // Create a new key
    if ($multiple) {
      $query[$key] = array(
        $value,
      );
    }
    else {
      $query[$key] = $value;
    }
  }
  return url(implode('/', $path), array(
    'query' => $query,
    'fragment' => $fragment,
    'absolute' => TRUE,
  ));
}

Functions

Namesort descending Description
bef_checkbox Build a BEF checkbox -- very similar to theme_checkbox (http://api.drupal.org/api/function/theme_checkbox/6)
bef_replace_query_string_arg Replaces/adds a given query string argument to the current URL
theme_select_as_checkboxes Themes a select element as a set of checkboxes
theme_select_as_checkboxes_fieldset Themes a select element as a collection of checkboxes enclosed in a collapsible fieldset
theme_select_as_hidden Themes a select element as a series of hidden fields
theme_select_as_links Themes a select drop-down as a collection of links
theme_select_as_radios Themes a select drop-down as a collection of radio buttons
theme_select_as_radios_fieldset Themes a select element as a collection of radio buttons enclosed in a collapsible fieldset
theme_select_as_tree Themes a taxonomy-based exposed filter select element as a nested unordered list. Note: this routine depends on the '-' char prefixed on the term names by Views to determine depth.