Drupal 7: Hide a field depending on the value of a checkbox

I recently had the requirement to hide a horizontal tab in node display depending on the value of a checkbox i.e. Show tab X. For the horizontal tabs I was using the excellent Fieldgroup module.

In order to achieve the above, I created a little custom module and used the newly introduced in drupal 7 hook, hook_node_view_alter.

Here is the code that checks the value of the field, then unsets it. Please note that the checkbox needs to be included in the node display settings in order for it to become available in the $build variable. There is an extra check for isset, just to avoid some PHP notices.

<?php
function MYMODULE_node_view_alter(&$build) {
  if (isset(
$build['field_checkbox']['#items'][0]['value'] )) {
    if (
$build['field_field_checkbox']['#items'][0]['value'] == 0 ) {
      unset(
$build['field_checkbox']);
      unset(
$build['field_to_hide']);
    }
  }
}
?>

Once I unset the contents of the field, the horizontal tab was removed, as this is the default behavior when there is an empty field in tab's contents.

blog: 

Recent Comments

Forward by Dries Buytaert, Founder and Project Lead, Drupal; CTO Acquia.

Order now from:

Managing Expectations Podcast with DrupalEasy

Author Interview http://tinyurl.com/8a8nxno

We provide the most Shiny Drupal Bits & Pixels

Since Drupal 4.x

© 2014 Konordo Limited
Drupal Services provider.
All rights reserved.

Reg Nr. 12301661F
VAT Nr. CY10301661D

M. Director: Konstantin Ordoulidis

 

Get in touch

Latest Tweets

Submit
randomness