hook_form_alter form state problems

Created on 6 February 2011, almost 14 years ago
Updated 13 April 2023, over 1 year ago

I'm doing what I think is a pretty simple form alter to utilize D7's form_state, so I can conditionally show a field group, its like this:

function antonelli_form_endoscopy_record_node_form_alter(&$form, &$form_state) {
	
  // fieldset colonoscopy
  $form['#fieldgroups']['group_colonoscopy'] = array(
    '#states' => array(
      'visible' => array(
        '#edit-field-procedure-und' => array('value' => t('colonoscopy')),
      ),
    ),
  );
  
  // fieldset gastroscopy
  $form['#fieldgroups']['group_gastroscopy'] = array(
    '#states' => array(
      'visible' => array(
        '#edit-field-procedure-und' => array('value' => t('gastroscopy')),
      ),
    ),
  );

  // print kpr($form);
}

The problem is the fieldgroups disappear entirely from the form, not just hidden, they are not printed at all, and I don't really understand why not because I have done this before with another form.

Any pointers much appreciated.

💬 Support request
Status

Closed: works as designed

Version

3.0

Component

discussion

Created by

🇳🇿New Zealand Jeff Burnz

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇬🇧United Kingdom lind101

    For those landing here looking for a way to add #states to field_groups in a more generic way via traditional form_alter_hooks, the below helper hook works well.

    /**
     * Implements hook_field_group_form_process().
     */
    function my_module_field_group_form_process(array &$element, &$group, &$complete_form) {
      /**
       * Provides a generic way for assigning Form API #states to field group elements
       *
       * @usage - In a from_alter hook the Group object can be added to include a form_api_states property,
       *          which is picked up here and applied to the field group element
       * @code
       *  $form['#fieldgroups']['group_my_group']->form_api_states = [
       *     'visible' => [
       *        ':input[name^="my_field_name"]' => ['checked' => TRUE],
       *      ]
       *    ];
       * @endcode
       */
      if (isset($group->form_api_states) && is_array($group->form_api_states) && !isset($element['#states'])) {
        $element['#states'] = $group->form_api_states;
      }
    }
    
  • 🇪🇨Ecuador dmezquia UTC-5

    The hook hook_field_group_form_process works ok for me too.

Production build 0.71.5 2024