Easy way to hide a field group including children

Public

</> CopyGet raw version
php
  1. function MODULE_form_node_form_alter(&$form, &$form_state) {
  2. if (!user_access('admin_role_name')) {
  3. field_group_hide_field_groups($form, array('group_for_admin_name'));
  4. }
  5. }

Comments

timonweb's picture

Great tip, but there is one note, function field_group_hide_field_groups is in dev version of module, but not in latest stable (1.1 to date). So if you want to use this trick, you need to add field_group_hide_field_groups to your custom module at first, like this:

  1. /**
  2.  * Hides field groups including children in a render array.
  3.  *
  4.  * @param array $element
  5.  * A render array. Can be a form, node, user, ...
  6.  * @param array $group_names
  7.  * An array of field group names that should be hidden.
  8.  */
  9. function MY_MODULE_field_group_hide_field_groups(&$element, $group_names) {
  10. foreach ($group_names as $group_name) {
  11. if (isset($element['#fieldgroups'][$group_name]) && isset($element['#group_children'])) {
  12. // Hide the field group.
  13. $element['#fieldgroups'][$group_name]->format_type = 'hidden';
  14. // Hide the elements inside the field group.
  15. foreach (array_keys($element['#group_children'], $group_name) as $field_name) {
  16. $element[$field_name]['#access'] = FALSE;
  17. }
  18. }
  19. }
  20. }

and then use snippet above as

  1. function MY_MODULE_form_node_form_alter(&$form, &$form_state) {
  2. if (!user_access('admin_role_name')) {
  3. MY_MODULE_field_group_hide_field_groups($form, array('group_for_admin_name'));
  4. }
  5. }
Felix Eve's picture

Use this function to hide sub groups as well:

  1. function MY_MODULE_field_group_hide_field_groups(&$form, $group_names) {
  2. foreach ($group_names as $group_name) {
  3. if (isset($form['#fieldgroups'][$group_name]) && isset($form['#group_children'])) {
  4. $form['#fieldgroups'][$group_name]->format_type = 'hidden';
  5. foreach (array_keys($form['#group_children'], $group_name) as $field_name) {
  6. if (isset($form['#fieldgroups'][$field_name])) {
  7. $sub_groups[] = $field_name;
  8. } else {
  9. $form[$field_name]['#access'] = FALSE;
  10. }
  11. }
  12. accident_report_field_group_hide_field_groups($form, $sub_groups);
  13. }
  14. }
  15. }
berliner's picture

Very nice info. The function is now also available in the stable releases (currently 1.3).
Thanks for the post!