You are here

public function FormAjaxSubscriber::onException in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber::onException()

Catches a form AJAX exception and build a response from it.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event: The event to process.

File

core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php, line 76
Contains \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber.

Class

FormAjaxSubscriber
Wraps AJAX form submissions that are triggered via an exception.

Namespace

Drupal\Core\Form\EventSubscriber

Code

public function onException(GetResponseForExceptionEvent $event) {
  $exception = $event
    ->getException();
  $request = $event
    ->getRequest();

  // Render a nice error message in case we have a file upload which exceeds
  // the configured upload limit.
  if ($exception instanceof BrokenPostRequestException && $request->query
    ->has(FormBuilderInterface::AJAX_FORM_REQUEST)) {
    $this
      ->drupalSetMessage($this
      ->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', [
      '@size' => $this
        ->formatSize($exception
        ->getSize()),
    ]), 'error');
    $response = new AjaxResponse();
    $status_messages = [
      '#type' => 'status_messages',
    ];
    $response
      ->addCommand(new ReplaceCommand(NULL, $status_messages));
    $response->headers
      ->set('X-Status-Code', 200);
    $event
      ->setResponse($response);
    return;
  }

  // Extract the form AJAX exception (it may have been passed to another
  // exception before reaching here).
  if ($exception = $this
    ->getFormAjaxException($exception)) {
    $request = $event
      ->getRequest();
    $form = $exception
      ->getForm();
    $form_state = $exception
      ->getFormState();

    // Set the build ID from the request as the old build ID on the form.
    $form['#build_id_old'] = $request
      ->get('form_build_id');
    try {
      $response = $this->formAjaxResponseBuilder
        ->buildResponse($request, $form, $form_state, []);

      // Since this response is being set in place of an exception, explicitly
      // mark this as a 200 status.
      $response->headers
        ->set('X-Status-Code', 200);
      $event
        ->setResponse($response);
    } catch (\Exception $e) {

      // Otherwise, replace the existing exception with the new one.
      $event
        ->setException($e);
    }
  }
}