Advertising sustains the DA. Ads are hidden for members. Join today

HowTos

Add a markup element to a Views Exposed Filter form

Last updated on
11 March 2021

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

This documentation needs work. See "Help improve this page" in the sidebar.

This page shows an example of how to modify a form created by a Views exposed filter.

The specific example involves adding a markup element to two forms generated by two pages inside the same View. This was developed following a requirement to add a new button next to the Submit button that would take the user to another page. That page would have another form with a button back to the first page

The steps involved are:

  1. Add a new function using hook_form_alter to the template.php file in your site's theme.
  2. Identify the View and the Display that is generating the form.
  3. Alter the form with your custom markup element.

The function will look something like this:

function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
  case 'views_exposed_form':
    $view = $form_state['view'];
    if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYNAME1') { 
        $form['views_exposed_form'] = array(
           '#markup' => '<div class="YOUR_CLASSES"><a href="/link-target">Link Label1</a></div>',
        );
    }
    if ($view->name == 'VIEWNAME' && $view->current_display == 'DISPLAYNAME2') { 
        $form['views_exposed_form'] = array(
           '#markup' => '<div class="YOUR_CLASSES"><a href="/link-target-2">Link Label2</a></div>',
        );
    }
    break;
  }
}

Looking at this more closely, the function does several things.

  • Gets the ID of the form on the current page. This will be done on all pages, not just those with forms.
  • Uses the case statement to establish if the current form (if there is one) is a views_exposed_form.
  • Assuming it is, it then checks the View and the Display. These are the machine names of each, not the CSS ID or class names.
  • For example, this is the edit URL for a specific views display. The view is called nearby and the display is called page:
admin/structure/views/view/nearby/edit/page
  • From there, we add the #markup element to the specific form - this happens to two separate forms in the same view.

Note that this example has been designed to allow you to hook_form_alter other forms using the switch/case syntax, although the example as provided only alters one form - the views_exposed_form. It would be relatively easy to add additional case statements for different forms (not just Views forms).

Help improve this page

Page status: Needs work

You can: