I have a Field Group fieldset named group_p_payment as machine name. I want to hide this based on the user. I tried the following code:

        $user = \Drupal::currentUser()->getRoles();
        if(!in_array("Administrator", $user) ||  !in_array("administer", $user)) {
         $form['group_p_payment']['#access'] = FALSE;

But it didn't work it. How can I hide the fieldset?

  • Also field_set id not visible in drupal 8 , unlike in drupal 6 which is visible – Crazyrubixfan Aug 8 '16 at 11:28

The field group module is no longer storing grouped fields as a fieldset in Drupal 8. It's storing metadata on each group in an array called #fieldgroups which is used in a pre-render function.

The logic of the module doesn't render the fieldset if all its children elements aren't visible. Hence, you can hide all the children elements to have the same effect. For example:

foreach ($form['#fieldgroups']['group_p_payment']->children as $form_element_id) {
  $form[$form_element_id]['#access'] = FALSE;

The logic will have to change if you have nested groups, but the approach will remain the same.

  • When i give like this i have to give all element id's of the group inside the loop. Instead i tried unset($form['#fieldgroups']['group_p_payment'] in the form alter. That worked , but give some notice error in field_group.module – Crazyrubixfan Aug 9 '16 at 4:28
  • Thanks your solution works without any notice (without any modification in module file ;) ) . – Crazyrubixfan Aug 9 '16 at 7:36
  • Notice: Undefined index: #fieldgroups... on a form with tabs. Thoughts? – Chris Happy May 24 '18 at 20:57
  • It's a notice, wrap your code in an isset check if you need more robust logic, or ignore it. – Shawn Conn May 24 '18 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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