0

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']->children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = TRUE;
}
// Second try
foreach ($form['#fieldgroups']['group_employment']->children as $form_element_id) {
  $form[$form_element_id]['#attributes']['disabled'] = 'disabled';
}

How can I disable fieldsets?

1
  • you work with field_group module ?
    – berramou
    Commented Nov 6, 2018 at 21:43

1 Answer 1

0

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;
}
2
  • How can I disable the fieldgroup? I can unset them successfully but how can I set the disable attribute?
    – vp85
    Commented Nov 7, 2018 at 13:53
  • i edited my answer check it out.
    – berramou
    Commented Nov 7, 2018 at 14:41

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.