W3cubDocs

/Drupal 8

public function FormAjaxSubscriber::onException

public FormAjaxSubscriber::onException(GetResponseForExceptionEvent $event)

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 71

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);
    }
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!EventSubscriber!FormAjaxSubscriber.php/function/FormAjaxSubscriber::onException/8.1.x