You can not access directly to #fieldgroups
in form_alter
you should add pre_render
function like the following:
function mymodule_form_alter(&$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']->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']->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;
}