How do I disable a fieldset? I read How to unset fieldset in hook_form_alter? to disable fieldsets in an hook_form_alter() implementation, but it didn't work.

I tried using the following code, but neither of them worked.

// First try.
foreach ($form['#fieldgroups']['group_employment']-&gt;children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = TRUE;
}




// Second try
foreach ($form['#fieldgroups']['group_employment']-&gt;children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = 'disabled';
}


How can I disable fieldsets?
You can not access directly to #fieldgroups in form_alter you should add pre_render function like the following:

function mymodule_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['#pre_render'][] = 'mymodule_form_pre_render';
  }
}

/**
 * @param $form
 *
 * @return mixed
 */
function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']-&gt;children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
  return $form;
}


Edit :
if you want to just disable the fields change the pre_render function by:

function mymodule_form_pre_render($form) {
  foreach ($form['#fieldgroups']['group_employment']-&gt;children as $form_element_id) {
    if (isset($form[$form_element_id])) {
      //- For entity reference fields
      if (isset($form[$form_element_id]['widget'][0]['target_id'])) {
        $form[$form_element_id]['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
      }
      //- For normal input form
      if (isset($form[$form_element_id]['widget'][0]['value'])) {
        $form[$form_element_id]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
      }
    }
  }
  return $form;
}