You are here

public static function SubmitButtonAjax::formAjaxCallback in Flexiform 8

Submit AJAX callback for a form.

File

src/Plugin/FormEnhancer/SubmitButtonAjax.php, line 136

Class

SubmitButtonAjax
FormEnhancer for altering the ajax settings of submit buttons.

Namespace

Drupal\flexiform\Plugin\FormEnhancer

Code

public static function formAjaxCallback($form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $wrapper = (isset($form['#build_id_old']) ? $form['#build_id_old'] : $form['#build_id']) . '-ajax-wrapper';
  if (!$form_state
    ->isExecuted()) {
    $response
      ->addCommand(new InsertCommand('#' . $wrapper, $form));
    $response
      ->addCommand(new PrependCommand('#' . $form['#build_id'] . '-ajax-wrapper', [
      '#type' => 'status_messages',
    ]));
    return $response;
  }
  $button = $form_state
    ->getTriggeringElement();
  $ajax_settings = $button['#ajax']['flexiform'];
  switch ($ajax_settings['response']) {
    case 'refresh':
      $build_info = $form_state
        ->getBuildInfo();
      $new_form_state = new FormState();
      $new_form_state
        ->addBuildInfo('args', $build_info['args']);
      $new_form_state
        ->setUserInput([]);
      $new_form = \Drupal::formBuilder()
        ->buildForm(!empty($build_info['callback_object']) ? $build_info['callback_object'] : $build_info['form_id'], $new_form_state);
      $response
        ->addCommand(new InsertCommand('#' . $wrapper, $new_form));
      $response
        ->addCommand(new PrependCommand('#' . $new_form['#build_id'] . '-ajax-wrapper', [
        '#type' => 'status_messages',
      ]));
      break;
    case 'reload':
      $response
        ->addCommand(new ReloadCommand());
      break;
    case 'redirect':
      $redirect_disabled = $form_state
        ->isRedirectdisabled();
      $form_state
        ->disableRedirect(FALSE);
      if ($redirect = $form_state
        ->getRedirect()) {
        $url = '';
        if ($redirect instanceof Url) {
          $url = $redirect
            ->toString();
        }
        elseif ($redirect instanceof RedirectResponse) {
          $url = $redirect
            ->getTargetUrl();
        }
        $response
          ->addCommand(new RedirectCommand($url));
      }
      else {
        $response
          ->addCommand(new ReloadCommand());
      }
      $form_state
        ->disableRedirect($redirect_disabled);
      break;
  }
  return $response;
}