Thursday, June 23, 2011

Change Views Exposed Filter Form Select Element To A List Of Checkboxes

Three steps for doing this.
/**
* Implementation of HOOK_theme.
*
* @return array An array of theme hooks.
*/
function mymodule_hooks_theme() {
return array(
'select_as_checkboxes' => array(
'function' => 'theme_select_as_checkboxes'
),
);
}

/**
* Implementation of HOOK_form_alter().
*
* @param array $form The form
* @param string $form_state The current state of the form.
*/
function mymodule_hooks_form_views_exposed_form_alter(&$form, &$form_state)
{
// We only want to change a certain form, so stop Drupal looking at any
// other exposed view form
if ($form['#id'] == 'views-exposed-form-myview-page-1') {
// Make the select box appear as a list of checkboxes
$form['formelement']['#theme'] = 'select_as_checkboxes';
$form['anotherformelement']['#theme'] = 'select_as_checkboxes';
}
}

function theme_select_as_checkboxes($element) {
$output = '';

$selected_options = (array) $element['#post'][$element['#name']]; // the selected keys from #options

foreach($element['#options'] as $key => $value) {

$id = $element['#id'] . '-' . $key; // custom

// is this option selected?
$selected = (array_search($key, $selected_options) !== false); // (returns key or false)

$checkbox = '';

$output .= '' . "\n";
}
return theme_form_element($element, $output); // wraps it neatly
}

1 comment: