You are here

function group_form_alter in Group 8

Same name and namespace in other branches
  1. 2.0.x group.module \group_form_alter()

Implements hook_form_alter().

File

./group.module, line 545
Allows you to group users, content and other entities.

Code

function group_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // GroupContentController::createForm() tends to load entity forms for adding
  // entities to a group. We need to add or alter the submit handlers of those
  // forms for the process to work properly.
  if ($form_state
    ->has('group_wizard') && $form_state
    ->get('group_wizard_id') == 'group_entity') {
    if ($wizard = $form_state
      ->get('group_wizard')) {
      $store = \Drupal::service('tempstore.private')
        ->get($form_state
        ->get('group_wizard_id'));
      $store_id = $form_state
        ->get('store_id');

      // Bail out if we are on step 2 of the wizard. We only want to alter the
      // submit handlers for the first step or if we are not in a wizard.
      if ($store
        ->get("{$store_id}:step") === 2) {
        return;
      }
    }
    foreach (Element::children($form['actions']) as $name) {

      // Remove preview button as it redirects back to the wrong form.
      if ($name == 'preview') {
        unset($form['actions'][$name]);
        continue;
      }

      // Skip buttons without submit handlers.
      if (empty($form['actions'][$name]['#submit'])) {
        continue;
      }

      // Skip buttons that do not properly build and save an entity.
      $submit = $form['actions'][$name]['#submit'];
      if (!in_array('::submitForm', $submit) || !in_array('::save', $submit)) {
        continue;
      }

      // If we are using the wizard, we need to substitute the entity save
      // handler in order to add the entity to the private temp store.
      if ($wizard) {
        foreach ($submit as $key => $handler) {
          if ($handler == '::save') {
            $form['actions'][$name]['#submit'][$key] = 'group_content_wizard_store';
          }
        }
      }
      else {
        $form['actions'][$name]['#submit'][] = 'group_content_entity_submit';
      }
    }

    // If we are using the wizard, we also add a cancel button to step 1.
    if ($wizard) {
      $form['actions']['cancel'] = [
        '#type' => 'submit',
        '#value' => t('Cancel'),
        '#submit' => [
          'group_content_wizard_cancel',
        ],
        '#limit_validation_errors' => [],
      ];
    }
  }
}