Programmatically Hiding A Fieldgroup On A Node Display in Drupal 7

If you have a fieldgroup in a node, you may want to hide it on some conditions. Here's how to do that programmatically. At first, we need to preprocess our node like this:

1
2
3
4
5
  1. /**
  2. * Implements hook_preprocess_HOOK().
  3. */
  4. function MODULE_NAME_preprocess_node(&$variables) {
  5. }

The tricky part starts here, if you'll google for "hide a fieldgroup" you'll get lots of results referencing a usage of field_group_hide_field_groups() like this snippet: http://dropbucket.org/node/130.

While this function perfectly works on forms it is useless if you apply it in hook_preprocess_node() (at least I couldn't make it work). The problem is fieldgroup uses 'field_group_build_pre_render' function that is get called at the end of the preprocessing call and populates your $variables['content'] with a field group and its children, so you can't alter this in hook_preprocess_node(). But as always in Drupal there's a workaround. At first let's define some simple logic in our preprocess_node() to determine if we want to hide a field group:

1
2
3
4
5
6
7
8
9
  1. /**
  2. * Implements hook_preprocess_HOOK().
  3. */
  4. function MODULE_NAME_preprocess_node(&$variables) {
  5. if ($variables['uid'] != 1) {
  6. // You can call this variable any way you want, just put it into $variables['element'] and set as TRUE.
  7. $variables['element']['hide_admin_field_group'] = TRUE;
  8. }
  9. }

Ok, so if user's id is not 1 we want to hide some fantasy 'admin_field_group'. We define logic here and pass result into elements array that is to be used later. As I previously noted, field group uses 'field_group_build_pre_render' to combine fields into a group, so we just need to alter this call in our module:

1
2
3
4
5
6
7
8
  1. /**
  2. * Hide admin field group on a node display.
  3. */
  4. function MODULE_NAME_field_group_build_pre_render_alter(&$element) {
  5. if (isset($element['hide_admin_field_group']) && isset($element['hide_admin_field_group'])) {
  6. $element['hide_admin_field_group']['#access'] = FALSE;
  7. }
  8. }

We made a check for our condition and if it is met, we set field group's access to FALSE that means: hide the field group. So now you should have a field group hidden on your node display. Of course, this example is the simplest case, you may add dependencies on node view_mode, content type and other conditions, so sky is the limit here. You can find and copy this snippet at dropbucket: http://dropbucket.org/node/927 I wonder, if you have another way of doing this?