Thursday, December 8, 2011

show/hide table column in drupal view by jquery

My note on how to toggle show/hide table column in drupal's view.

View 3 on drupal 7 produce html like this

<table class="views-table cols-4">
  <thead> <tr>
    <th class="views-field views-field-title">Example</th>
    <th class="views-field views-field-body">howto</th>
    <th class="views-field views-field-field-1">dynamically</th>
    <th class="views-field views-field-field-2">show/hide</th>
    <tr class="odd views-row-first views-row-last">
      <td class="views-field views-field-title">table column</td>
      <td class="views-field views-field-body">Drupal</td>
      <td class="views-field views-field-3">Views</td>
      <td class="views-field views-field-4">jquery</td>

go to view edit page
Displays -> Page Details -> Page Settings -> Footer
add the following code

Show columns
<input onclick="toggleVis(this, '.views-field-title')" type="checkbox"> Title
<input onclick="toggleVis(this, '.views-field-body')" type="checkbox"> Body

<script type="text/javascript">
  function toggleVis(chkbox, col){
    if(chkbox.checked == true) {jQuery(col).show();}
    else {jQuery(col).hide();}

Some might prefer FAPI like this
function showhide_column_form($form, &$form_state) {

  $form['column_visible'] = array(
    '#type' => 'fieldset',
    '#title' => 'Show/Hide column',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,

  $form['column_visible']['id'] = array(
    '#type' => 'checkbox',
    '#title' => 'column1',
    '#default_value' => 1,
    '#attributes' => array('onclick' =>"toggleVis(this, '.views-field-title');"),

  return $form;
Then replace the previous HTML form by this
print drupal_render(drupal_get_form('showhide_column_form'));

For me, accessing .module is faster than the view edit page
function my_module_form_views_exposed_form_alter(&$form,&$form_state)
  if($form['#id'] == 'views-exposed-form-my-search-page') {

    $inline_script = '
      <style type="text/css">
      .views-field-1 { display: none; }
      .views-field-2 { display: none; }

      <script type="text/javascript">
        function toggleVis(chkbox,col){
         if(chkbox.checked == true) { jQuery(col).show(); }
         else {jQuery(col).hide(); }

    $element = array(
      '#type' => 'markup',
      '#markup' => $inline_script,

    drupal_add_html_head($element, 'css');

The Drupal community

related post about jquery

No comments:

Post a Comment