I have a field group that should only be accessible for a privileged user role. I have been looking for a method to easily deny access to some specific field groups, but the solution I found is rather long winded. Is there an easier way to accomplish this?

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_node_form_alter(&$form, &$form_state) {
  global $user;

  // The 'internal' field groups should only be accessible for regional administrators.
  if (!in_array('regional administrator', $user->roles)) {
    foreach (array('group_action_internal', 'group_company_internal', 'group_topic_internal') as $fieldgroup) {
      if (isset($form['#fieldgroups'][$fieldgroup]) && isset($form['#group_children'])) {
        // Hide the field group itself.
        $form['#fieldgroups'][$fieldgroup]->format_type = 'hidden';
        // Hide the elements inside the field group.
        foreach ($form['#group_children'] as $field => $group) {
          if ($group == $fieldgroup) {
            $form[$field]['#access'] = FALSE;
          }
        }
      }
    }
  }
}

Comments

pfrenssen’s picture

Title: Easy way to deny access to a field group » Easy way to hide a field group including children in hook_form_alter
StatusFileSize
new1.32 KB

I needed this again for a new project. I got into the habit of putting all administrator-specific fields into a single "Internal" field group so they can be easily hidden using hook_form_alter() and a function call. I rolled this in a patch.

Example usage: hide the 'group_user_internal' field group on the user profile form.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  global $user;

  // Hide the 'Internal' field group for unprivileged users.
  if ($user->uid != 1 && !in_array('administrator', $user->roles)) {
    field_group_hide_field_groups($form, array('group_user_internal'));
  }
}
damien_vancouver’s picture

+1 This function works great for me!

nicolash’s picture

Nice. Haven't patched the module, but using the basic approach in a custom module.

If the allowed roles would be configurable in the settings interface, this could be a nice simple way to hide/limit access to certain fields in situations where full field permission approaches are overkill.

Would the maintainer be interested in a patch for this?

guile2912’s picture

Patch worked fine with Field group 7.x-1.1
This simple function is really usefull, I would definitly like to have in the module.

nils.destoop’s picture

Status: Active » Fixed

Tested the patch, and it works good. I changed the form parameter to $element. Because you can also hide groups on display side, with this function.

Also added it to our api.php file.
#3 If you create a patch for this, we will be happy to review it.

pfrenssen’s picture

Nice, thanks for adding it! A small remark, if it is not too much trouble for you, could you credit people for their patches? I love seeing my name in the commit history. It flatters my ego, and motivates me to contribute more in the future.

Here is some relevant information:

Thanks!! :)

nils.destoop’s picture

Ok, i'll do from now :)

amitaibu’s picture

Is it going to be committed also to 2.x?

restyler’s picture

Status: Fixed » Active

In latest dev, there is an error:

you need to change

function field_group_hide_field_groups(&$element, $group_names) {  

to

function field_group_hide_field_groups(&$form, $group_names) {  

(or, it's better to do an opposite thing - refactor $form vars to $element vars everywhere in the function)

smk-ka’s picture

Category: support » bug
Status: Active » Needs review
StatusFileSize
new1.01 KB

No brainer.

Stalski’s picture

Status: Needs review » Fixed

This is pushed to git. Thx for the patch

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

JonathanHindi’s picture

Just a question is this API Function rolled to the latest 7.x-1.1 version or I have to patch it or use the dev version?

xurizaemon’s picture

@jonathanhindi - On the module page you can see that 7.x-1.1 is dated October 2011, while the git commit above is dated May 2012, so you can tell the patch won't be in there. If dates don't make it obvious, the next step is to check Git (7.x-1.1 for that tarball) for the commit or code you want (visible on 7.x-1.x @ 2012-05-31, but not on 7.x-1.1).

Stalski’s picture

Just answering to amitai: no, branch 2 is no longer supported and is being merged into 7.x-1.x this weekend.

jan.s’s picture

Status: Closed (fixed) » Needs work

This is not working for nested groups. Only the group itself and the fields in the group are hidden. All further groups inside the group are still being shown. This should be fixed.

jcisio’s picture

Title: Easy way to hide a field group including children in hook_form_alter » Easy way to hide a field group including children (with nested group) in hook_form_alter
Category: bug » feature
Status: Needs work » Active

There is no patch for nested group. Make it as active.

hibersh’s picture

Status: Active » Needs review
StatusFileSize
new812 bytes

Nested support

duaelfr’s picture

Status: Needs review » Reviewed & tested by the community

Thank you hibersh !

trgreen17’s picture

Love the module, use it on every site. Thanks for creating it. I'm trying to hide a fieldset and everything in it from anyone who is not logged in. (I like to keep taxonomy terms and whatnot in a fieldset for my use only.) I feel like I'm so close... a little help please?

Anyway, I successfully applied the patch to the 7.x-1.x-dev version, but I don't know how to use it. I opened the field_group.module and went to line 1787 and added this code above the function "field_group_hide_field_groups":

$group_names = array("group_metadata");

Cleared caches and visited in another browser, not logged in. Fieldset is still there. Do I need to define $element too? If so, how do I find the element?

And the last question is... this doesn't seem to take into account whether someone is logged in. Again, I just want to hide the fieldset and all its contents from anonymous visitors.

Thanks for any and all help!

thirdender’s picture

StatusFileSize
new10 KB

@trgreen23: You'll need to call the function from your own custom module. Create a new module using the attached as a template. This module implements HOOK_form_alter to call the field_group_hide_field_groups function when a form is being built. The form is passed to the hook as an argument, and that variable is what is passed to field_group_hide_field_groups. Hope this helps :-)

thirdender’s picture

This is a really useful function, and I'm using it pretty extensively on a site I'm developing right now. I'm developing a site where forms are assigned to users to complete. This means an initial creation step where some fields are visible, and a second step where the second user edits other fields. Now that I'm writing all of this down, I'm realizing that this probably could have been done slicker with Field Collection and Field Permissions, but that's not how I started doing everything…

I have a custom module that shows/hides field groups based on user roles, and it's working good. However, that means all the configuration is happening in my custom PHP. Would there be any interest in adding show/hide per role options on the field group settings form?

mel-miller’s picture

Could anyone help me modify this concept (or point me in another direction) to hide a tab based on different criteria?

Specifically, I have a viewfield within a tab item as part of a horizontal display tabset. The view I am referencing uses a contextual filter. I would like to hide the tab when the view does not return any results. The contextual filter is set to not render the view when it does not validate or when the filter is not available. However, the field with the view in it gets rendered regardless even though it is empty. Therefore the field is not empty and the containing display tab gets rendered.

mel-miller’s picture

Disregard #23, the problem was a bug in viewfield: https://drupal.org/node/477244.

nils.destoop’s picture

Status: Reviewed & tested by the community » Fixed

Thx for the patch. Pushed to dev.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

sachbearbeiter’s picture

Issue summary: View changes

Thx - very useful ...

smartsystems160’s picture

#1 works for me, i am not using nested field groups. Just a note, I was thinking the code would be included in the module so that fieldgroups can be exposed in the user permissions page and admin can select roles which can access fieldgroups, similar to what User Role Field and Field Permissions do

johnhanley’s picture

I'm using Redhen CRM to render custom fields during registration and want to hide certain fieldsets until after authentication. In other words on subsequent visits to the user edit page.

I'm trying to hide some nested fieldsets on the user registration form, but without success.

function custom_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  if (!user_is_logged_in()) {
    field_group_hide_field_groups($form, array('group_volunteer'));
  }
}

Looking at the contents of $form before calling field_group_hide_field_groups(), I don't even see the fieldset elements--or any of the custom fields for that matter. I suspect Redhen CRM is adding the custom fields very late in the build.

I've been investigating this for awhile without success and maybe my focus is waning. Does anyone have any ideas how to accomplish this?

jospratiklive’s picture

#1 comment worked nice.

Thanks @pfrenssen!

akolahi’s picture

For those you you who are doing something with the hidden fields (for example setting a default value) the above wont work. $element[$field_name]['#access'] = FALSE; sets #access to FALSE, which according to documentation "when FALSE, the element is not rendered and the user submitted value is not taken into consideration." Thus if you are feeding a value into it in someway or another, it will lose the value. This can particularly be an issue if the field is required. If this is the case for you, a slight modification of the function in a custom module can resolve it:

function my_custom_module_hide_field_groups(&$form, $group_names) {
	foreach ($group_names as $group_name) {
		if (isset($form['#fieldgroups'][$group_name]) && isset($form['#group_children'])) {
		// Hide the field group.
			$form['#fieldgroups'][$group_name]->format_type = 'hidden';
			// Hide the elements inside the field group.
			foreach (array_keys($form['#group_children'], $group_name) as $field_name) {
			$form[$field_name]['#prefix'] = '<div style="display:none;">';
			$form[$field_name]['#suffix'] = '</div>';
			}
		}
	}
}

Depending on your security requirements this solution might be a good fit. Just note that the field is being hidden by css, which can be disabled by a savvy user.

Rob_Feature’s picture

Category: Feature request » Bug report
Status: Closed (fixed) » Needs work

I realize this is really old, but using the latest dev, you can't hide more than 1 fieldgroup at a time with the array. I put more than 1 fieldgroup like this and it doesn't work:field_group_hide_field_groups($form, array('group_group_1, group_group_2'));

If I just call this function twice (one for each group) it works fine. I noticed none of the examples above tried to use more than 1 group in that array.

Edit: Mistype! Realized I missed the internal commas in the array!

Rob_Feature’s picture

Category: Bug report » Feature request
Status: Needs work » Closed (fixed)

Putting everything back to fixed after realizing my error above. (sure would be nice to be able to delete a comment!)

dunebl’s picture

Title: Easy way to hide a field group including children (with nested group) in hook_form_alter » Not working with field-collection having multiple values (and groups)

My case is the following: a field-collection (FC) containing several fieldset groups (G1, G2,...), let say I would like to hide G1
If FC contains only one value "field_group_hide_field_groups" is running as expected

FC[0]
  G-0-1
      Field-1-1
      -Field-1-2
  G-0-2
      Field-0-2-1
      Field-0-2-2

Result: G-0-1 and its content is hidden as expected
But, If FC contains several values then field_group_hide_field_groups does not work as expected.
Let say, I would like to hide G-0-1 (but not G-1-1)

FC[0]
  G-0-1
      Field-0-1-1
      Field-0-1-2
  G-0-2
      Field-0-2-1
      Field-0-2-2
FC[1]
  G-1-1
      Field-1-1-1
      Field-1-1-2
  G-1-2
      Field-1-2-1
      Field-1-2-2
...

Thus, when using "field_group_hide_field_groups", the result is the following:

  • The G-0-1 group is hidden as expected
  • There is a strange behaviour for the other G1 groups (G-1-1, G-2-1,...): the fields in those groups remains visible (expected) but the fieldset is hidden (and should not)

As this is a field collection, note that G-0-1 and G-1-1 have the same name (like G-0-2 and G-1-2). This is because if I create a field collection with a fieldset to group several fields, and, if I enable multiple values for this FC, I will have several groups with the same name...