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>
  </thead>
  <tbody>
    <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>
    </tr>
  </tbody>
</table>

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

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

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


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
<?php
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; }
      </style>

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

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

    drupal_add_html_head($element, 'css');
  }
}


Thanks:
The Drupal community
http://www.fiendish.demon.co.uk/html/javascript/hidetablecols.html

related post about jquery
http://stackoverflow.com/questions/4673267/hide-table-columns-automatically-by-checking-a-checkbox-with-jquery

No comments:

Post a Comment