You are here

public function AjaxAttachTrait::ajaxMultiplex in Ubercart 8.4

Ajax callback multiplexer.

Processes a set of Ajax commands attached to the triggering element.

File

uc_store/src/AjaxAttachTrait.php, line 164

Class

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

Namespace

Drupal\uc_store

Code

public function ajaxMultiplex(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // $attachments collects other AjaxResponse objects' attachments.
  $attachments = [];
  $element = $form_state
    ->getTriggeringElement();
  foreach ($element['#ajax']['list'] as $wrapper => $callback) {
    $callback = $form_state
      ->prepareCallback($callback);
    if (!empty($callback) && is_callable($callback) && ($result = call_user_func_array($callback, [
      $form,
      $form_state,
      $wrapper,
    ]))) {
      if ($result instanceof AjaxResponse) {

        // Merge the current AjaxResponse object's attachments into the
        // $attachments variable.
        $attachments = array_merge_recursive($attachments, $result
          ->getAttachments());

        // Merge AjaxResponse commands into our single list.
        foreach ($result
          ->getCommands() as $command) {
          $response
            ->addCommand(new CommandWrapper($command));
        }
      }
      elseif (is_string($wrapper)) {

        // Otherwise, assume the callback returned a string or render-array,
        // and insert it into the wrapper.
        $html = is_string($result) ? $result : drupal_render($result);
        $response
          ->addCommand(new ReplaceCommand('#' . $wrapper, trim($html)));
        $status_messages = [
          '#type' => 'status_messages',
        ];
        $response
          ->addCommand(new PrependCommand('#' . $wrapper, drupal_render($status_messages)));
      }
    }
  }

  // Set the collected attachments into newly created AjaxResponse object.
  $response
    ->setAttachments($attachments);
  return $response;
}