4

I am trying to use hook_form_alter() to change the way a form is displayed. The form has 4 fieldsets and I only want to display one of them. How can I make these fieldsets invisible using hook_form_alter()?

6 Answers 6

12

It's really simple.

On Drupal 6/7, set the "#access" property of the fieldset to FALSE, or use logic to determine visibility.
This will also hide all the content of the fieldset, and yet keep the values intact so that when the form is submitted they are not cleared, but retained.

3
  • Aye, discovering that saved me all kinds of time and pain. Plus it is super simple to use user_access('some perm') to control form elements safely in a complex system.
    – codexmas
    Commented Jun 16, 2011 at 4:02
  • 3
    this doesn't work for fieldsets in D7. fieldsets are in the #groups array and none that I'm seeing there have a #access property. Will continue digging but this answer doesn't appear to work for D7 & fieldsets.
    – Gold
    Commented May 13, 2013 at 22:21
  • One thing to note that I learned the hard way, but is clear in the docs: If you are populating a field a la a hook_form_alter ajax-based modification and you set #access to false, the value you set on the form will not be taken in. Only set #access to false if you are not also trying to save data from this form field. (see api.drupal.org/api/drupal/…)
    – cdmo
    Commented Sep 14, 2015 at 17:39
2

I found that you had to do the following:

$form['last_field_in_tabgroup']['#required'] = FALSE;

and

hide($form['last_field_in_tabgroup']);

to make sure an empty tab doesn't show.

0

I use the hide function, for instance

    hide($form['title']);

if you need to set certain parameters of the form before hiding it do it in this fashion

 $form['title']['#required'] = FALSE;
0

I have developed a module to do so: the Hide Group (fieldset) module.

The #access property has the effect to remove entirely the fieldset from the form; my module only set it to hidden via CSS styles.

0

Use hide($form['element']); and show($form['element']); if you want to be able to display the element later (for instance in a Dynamic / Ajax form).

Setting the #access property to False works for hiding the element, but it seems you can't subsequently set it True if you want to show it again.

0

When you unset the form fields inside fieldset it should not be shown automatically, but you can also implement hook_field_widget_WIDGET_TYPE_form_alter() in your module for other cases.

You can use this guide. https://3cwebservices.com/drupal/how-remove-fieldset-drupal-address-field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.