blog-banner

Creating a duplicate of view's exposed form programatically

  • Drupal
  • Drupal Planet
  • Views

View Exposed Drupal Filters

Views module being shipped with exposed filters feature since version 2.x. It does a great job of adding dynamic and complex filters to a view with no custom code. Filters specific to project needs could be implemented with a few lines of custom code. One such experience is what I would like to share in this blog post. 

Since Views 3.x, in addition to filters, sort criteria can be exposed as well. The exposed form can render in a separate block on the sidebar or content top as desired. Though it is one of the improvements, it had limitations when trying to address a requirement specific to our project. I wanted to show the exposed filters and sort forms in different blocks. Such that filter form in the sidebar and sort form in the content top region.

Initially, I attempted to render the block twice; one from standard Drupal block manager and the other from context. And a bit of CSS and jQuery to hide unwanted fields. I thought this worked but later realized that some of the basic usability features and jQuery functions were broken as a result of applying this trick. Also, the markup validity was messed up as the same id was used in both the blocks.

To produce the needed output I had to clone the exposed form, the code I used for the same looks as below,

  1.   $view_id = 'deals';
  2.   $display_id = 'page';
  3.   $view = views_get_view($view_id);
  4.   $view->set_display($display_id);
  5.   $view->init_handlers();
  6.   $form_state = array(
  7.     'view' => $view,
  8.     'display' => $view->display,
  9.     'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
  10.     'method' => 'get',
  11.     'rerender' => TRUE,
  12.     'no_redirect' => TRUE,
  13.   );
  14.   //$form = drupal_build_form('views_exposed_form', $form_state); //create the filter form
  15.   $form = views_exposed_form(array(), $form_state);
  16.   drupal_render($form['sort_by']);

To above code together with some jQuery snippets made it possible to achieve the desired output. Finding the right functions to clone the view exposed form was a kind of a challenge then. I hope the above snippet would help other developers to tackle similar requirements.

Get awesome tech content in your inbox