Drupal - Alter Views Exposed Filter Form


With hook_form_alter, we can adjust a Views Exposed Filter Form. For example, I had an exposed filter so users could select a particular node reference to filter on. However, the exposed filter was including unpublished nodes, and I needed to get rid of them. So with a little code like this, we can get the job done:

 * Implements hook_form_alter().
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'my_view_name' && $form_state['view']->current_display == 'my_view_display_name') {
    // Only show published nodes as options for the exposed filter.
    $sql = "SELECT nid, title FROM {node} WHERE status = 1 ORDER BY title ASC";
    $result = db_query($sql);
    $nodes = $result->fetchAll();
    $options = array('All' => '- Any -');
    foreach ($nodes as $node) {
      $options[$node->nid] = $node->title;
    $form['field_my_node_reference_nid']['#options'] = $options;

Check out this related article on how to theme an exposed filter: http://tylerfrankenstein.com/code/drupal-how-theme-views-exposed-filter-form


Thank you very much !

can it be possible to set exposed filter values from another view(call it secondary)? by passing contextual filter of primary view , say current logged user.

tyler's picture

Programmatically, yes. Through the Drupal UI, no I don't think so.

Add new comment