FormAjaxException example

// After processing the form, if this is an AJAX form request, interrupt     // form rendering and return by throwing an exception that contains the     // processed form and form state. This exception will be caught by     // \Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber::onException() and     // then passed through     // \Drupal\Core\Form\FormAjaxResponseBuilderInterface::buildResponse() to     // build a proper AJAX response.     // Only do this when the form ID matches, since there is no guarantee from     // $ajax_form_request that it's an AJAX request for this particular form.     if ($ajax_form_request && $form_state->isProcessingInput() && $request->request->get('form_id') == $form_id) {
      throw new FormAjaxException($form$form_state);
    }

    // If the form returns a response, skip subsequent page construction by     // throwing an exception.     // @see Drupal\Core\EventSubscriber\EnforcedFormResponseSubscriber     //     // @todo Exceptions should not be used for code flow control. However, the     // Form API does not integrate with the HTTP Kernel based architecture of     // Drupal 8. In order to resolve this issue properly it is necessary to     // completely separate form submission from rendering.     // @see https://www.drupal.org/node/2367555


  /** * @covers ::onException */
  public function testOnException() {
    $form = ['#type' => 'form', '#build_id' => 'the_build_id'];
    $expected_form = $form + [
      '#build_id_old' => 'the_build_id',
    ];
    $form_state = new FormState();
    $exception = new FormAjaxException($form$form_state);

    $request = new Request([]['form_build_id' => 'the_build_id']);
    $commands = [];
    $response = new Response('');

    $this->formAjaxResponseBuilder->expects($this->once())
      ->method('buildResponse')
      ->with($request$expected_form$form_state$commands)
      ->willReturn($response);

    $this->assertResponseFromException($request$exception$response);
    
Home | Imprint | This part of the site doesn't use cookies.