You are here

public function AjaxAttachTrait::ajaxProcessForm in Ubercart 8.4

Form process callback to allow multiple Ajax callbacks on form elements.

File

uc_store/src/AjaxAttachTrait.php, line 82

Class

AjaxAttachTrait
Helper functions for ajax behaviors on the checkout and order-edit forms.

Namespace

Drupal\uc_store

Code

public function ajaxProcessForm(array $form, FormStateInterface $form_state) {

  // When processing top level form, add any variable-defined pane wrappers.
  if (isset($form['#form_id'])) {
    switch ($form['#form_id']) {
      case 'uc_cart_checkout_form':
        $config = \Drupal::config('uc_cart.settings')
          ->get('ajax.checkout') ?: [];
        foreach ($config as $key => $panes) {
          foreach ($panes as $pane) {
            $form_state
              ->set([
              'uc_ajax',
              'uc_ajax',
              $key,
              $pane,
            ], '::ajaxReplaceCheckoutPane');
          }
        }
        break;
    }
  }
  if (!$form_state
    ->has('uc_ajax')) {
    return $form;
  }

  // We have to operate on the children rather than on the element itself, as
  // #process functions are called *after* form_handle_input_elements(),
  // which is where the triggering element is determined. If we haven't added
  // an '#ajax' key by that time, Drupal won't be able to determine which
  // callback to invoke.
  foreach (Element::children($form) as $child) {
    $element =& $form[$child];

    // Add this process function recursively to the children.
    if (empty($element['#process']) && !empty($element['#type'])) {

      // Ensure the default process functions for the element type are called.
      $info = element_info($element['#type']);
      if (!empty($info['#process'])) {
        $element['#process'] = $info['#process'];
      }
    }
    $element['#process'][] = [
      $this,
      'ajaxProcessForm',
    ];

    // Multiplex any Ajax calls for this element.
    $parents = $form['#array_parents'];
    array_push($parents, $child);
    $key = implode('][', $parents);
    $callbacks = [];
    foreach ($form_state
      ->get('uc_ajax') as $fields) {
      if (!empty($fields[$key])) {
        if (is_array($fields[$key])) {
          $callbacks = array_merge($callbacks, $fields[$key]);
        }
        else {
          $callbacks[] = $fields[$key];
        }
      }
    }
    if (!empty($callbacks)) {
      if (empty($element['#ajax'])) {
        $element['#ajax'] = [];
      }
      elseif (!empty($element['#ajax']['callback'])) {
        if (!empty($element['#ajax']['wrapper'])) {
          $callbacks[$element['#ajax']['wrapper']] = $element['#ajax']['callback'];
        }
        else {
          array_unshift($callbacks, $element['#ajax']['callback']);
        }
      }
      $element['#ajax'] = array_merge($element['#ajax'], [
        'callback' => [
          $this,
          'ajaxMultiplex',
        ],
        'list' => $callbacks,
      ]);
    }
  }
  return $form;
}