AjaxResponse example

public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  /** * Callback for testing MessageCommand with default settings. * * @return \Drupal\Core\Ajax\AjaxResponse * The AJAX response. */
  public function makeMessageDefault() {
    $response = new AjaxResponse();
    return $response->addCommand(new MessageCommand('I am a message in the default location.'));
  }

  /** * Callback for testing MessageCommand using an alternate message location. * * @return \Drupal\Core\Ajax\AjaxResponse * The AJAX response. */
  public function makeMessageAlternate() {
    $response = new AjaxResponse();
    

  public function __construct(TitleResolverInterface $title_resolver, RendererInterface $renderer$position = 'side') {
    parent::__construct($title_resolver$renderer);
    $this->renderer = $renderer;
    $this->position = $position;
  }

  /** * {@inheritdoc} */
  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    // First render the main content, because it might provide a title.     $content = $this->renderer->renderRoot($main_content);
    // Attach the library necessary for using the OpenOffCanvasDialogCommand and     // set the attachments for this Ajax response.     $main_content['#attached']['library'][] = 'core/drupal.dialog.off_canvas';
    $response->setAttachments($main_content['#attached']);

    // If the main content doesn't provide a title, use the title resolver.     $title = $main_content['#title'] ?? $this->titleResolver->getTitle($request$route_match->getRouteObject());

    

  public function updateFormCallback(array &$form, FormStateInterface $form_state) {
    $triggering_element = $form_state->getTriggeringElement();
    $wrapper_id = $triggering_element['#ajax']['wrapper'];
    $added_media = $form_state->get('media');

    $response = new AjaxResponse();

    // When the source field input contains errors, replace the existing form to     // let the user change the source field input. If the user input is valid,     // the entire modal is replaced with the second step of the form to show the     // form fields for each media item.     if ($form_state::hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $form));
      return $response;
    }

    // Check if the remove button is clicked.

  public function __construct(ElementInfoManagerInterface $element_info_manager, RendererInterface $renderer) {
    $this->elementInfoManager = $element_info_manager;
    $this->renderer = $renderer;
  }

  /** * {@inheritdoc} */
  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    if (isset($main_content['#type']) && ($main_content['#type'] == 'ajax')) {
      // Complex Ajax callbacks can return a result that contains an error       // message or a specific set of commands to send to the browser.       $main_content += $this->elementInfoManager->getInfo('ajax');
      $error = $main_content['#error'];
      if (!empty($error)) {
        // Fall back to some default message otherwise use the specific one.         if (!is_string($error)) {
          $error = 'An error occurred while handling the request: The server received invalid input.';
        }
        
return [
      '#markup' => 'Current theme: ' . \Drupal::theme()->getActiveTheme()->getName(),
    ];
  }

  /** * Returns an AjaxResponse; settings command set last. * * Helps verifying AjaxResponse reorders commands to ensure correct execution. */
  public function order() {
    $response = new AjaxResponse();
    // HTML insertion command.     $response->addCommand(new HtmlCommand('body', 'Hello, world!'));
    $build['#attached']['library'][] = 'ajax_test/order';
    $response->setAttachments($build['#attached']);

    return $response;
  }

  /** * Returns an AjaxResponse with alert command. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request object. * * @return \Drupal\Core\Ajax\AjaxResponse * The JSON response object. */
foreach ($this->bundleInfo->getBundleInfo($this->entityType->id()) as $bundle_id => $bundle) {
      if ($this->workflow->getTypePlugin()->appliesToEntityTypeAndBundle($this->entityType->id()$bundle_id)) {
        $selected_bundles[$bundle_id] = $bundle['label'];
      }
    }
    $selected_bundles_list = [
      '#theme' => 'item_list',
      '#items' => $selected_bundles,
      '#context' => ['list_style' => 'comma-list'],
      '#empty' => $this->t('none'),
    ];
    $response = new AjaxResponse();
    $response->addCommand(new CloseDialogCommand());
    $response->addCommand(new HtmlCommand('#selected-' . $this->entityType->id()$selected_bundles_list));
    return $response;
  }

  /** * Route title callback. */
  public function getTitle(WorkflowInterface $workflow = NULL, $entity_type_id) {
    $this->entityType = $this->entityTypeManager->getDefinition($entity_type_id);

    
/** * Util to render dialog in ajax callback. * * @param bool $is_modal * (optional) TRUE if modal, FALSE if plain dialog. Defaults to FALSE. * * @return \Drupal\Core\Ajax\AjaxResponse * An ajax response object. */
  protected function dialog($is_modal = FALSE) {
    $content = AjaxTestController::dialogContents();
    $response = new AjaxResponse();
    $title = $this->t('AJAX Dialog & contents');

    // Attach the library necessary for using the Open(Modal)DialogCommand and     // set the attachments for this Ajax response.     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';

    if ($is_modal) {
      $response->addCommand(new OpenModalDialogCommand($title$content));
    }
    else {
      $selector = '#ajax-test-dialog-wrapper-1';
      
$access = $entity_access->andIf($field_access);
    if ($access instanceof RefinableCacheableDependencyInterface) {
      $access->addCacheableDependency($state);
    }
    return $access;
  }

  /** * {@inheritdoc} */
  public function getSelectionResponse(MediaLibraryState $state, array $selected_ids) {
    $response = new AjaxResponse();

    $parameters = $state->getOpenerParameters();
    if (empty($parameters['field_widget_id'])) {
      throw new \InvalidArgumentException('field_widget_id parameter is missing.');
    }

    // Create a comma-separated list of media IDs, insert them in the hidden     // field of the widget, and trigger the field update via the hidden submit     // button.     $widget_id = $parameters['field_widget_id'];
    $ids = implode(',', $selected_ids);
    
return new static(
      $container->get('plugin.manager.media.source'),
      $container->get('entity_field.manager'),
      $container->get('entity_display.repository')
    );
  }

  /** * Ajax callback triggered by the type provider select element. */
  public function ajaxHandlerData(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#source-dependent', $form['source_dependent']));
    return $response;
  }

  /** * {@inheritdoc} */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form$form_state);

    // Source is not set when the entity is initially created.
use Drupal\Core\Form\FormStateInterface;

/** * Simple object for testing methods as Ajax callbacks. */
class Callbacks {

  /** * Ajax callback triggered by select. */
  public function selectCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax_selected_color', $form_state->getValue('select')));
    $response->addCommand(new DataCommand('#ajax_selected_color', 'form_state_value_select', $form_state->getValue('select')));
    return $response;
  }

  /** * Ajax callback triggered by date. */
  public function dateCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $date = $form_state->getValue('date');
    
// Add the special AJAX class if a new file was added.     $current_file_count = $form_state->get('file_upload_delta_initial');
    if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
      $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
    }

    $status_messages = ['#type' => 'status_messages'];
    $form['#prefix'] .= $renderer->renderRoot($status_messages);
    $output = $renderer->renderRoot($form);

    $response = new AjaxResponse();
    $response->setAttachments($form['#attached']);

    return $response->addCommand(new ReplaceCommand(NULL, $output));
  }

  /** * Render API callback: Expands the managed_file element type. * * Expands the file type to include Upload and Remove buttons, as well as * support for a default value. */
  

  public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    $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->messenger->addError($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())]));
      $response = new AjaxResponse(NULL, 200);
      $status_messages = ['#type' => 'status_messages'];
      $response->addCommand(new PrependCommand(NULL, $status_messages));
      $event->allowCustomResponseCode();
      $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();
      
use Symfony\Component\HttpFoundation\Request;

/** * Default main content renderer for modal dialog requests. */
class ModalRenderer extends DialogRenderer {

  /** * {@inheritdoc} */
  public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match) {
    $response = new AjaxResponse();

    // First render the main content, because it might provide a title.     $content = $this->renderer->renderRoot($main_content);

    // Attach the library necessary for using the OpenModalDialogCommand and set     // the attachments for this Ajax response.     $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $response->setAttachments($main_content['#attached']);

    // If the main content doesn't provide a title, use the title resolver.     $title = $main_content['#title'] ?? $this->titleResolver->getTitle($request$route_match->getRouteObject());

    
$field_id = $form_state->getTriggeringElement()['#field_id'];
    $selected_ids = $form_state->getValue($field_id);
    $selected_ids = $selected_ids ? array_filter(explode(',', $selected_ids)) : [];

    // Allow the opener service to handle the selection.     $state = MediaLibraryState::fromRequest($request);

    $current_selection = $form_state->getValue('media_library_select_form_selection');
    $available_slots = $state->getAvailableSlots();
    $selected_count = count(explode(',', $current_selection));
    if ($available_slots > 0 && $selected_count > $available_slots) {
      $response = new AjaxResponse();
      $error = \Drupal::translation()->formatPlural($selected_count - $available_slots, 'There are currently @total items selected. The maximum number of items for the field is @max. Please remove @count item from the selection.', 'There are currently @total items selected. The maximum number of items for the field is @max. Please remove @count items from the selection.', [
        '@total' => $selected_count,
        '@max' => $available_slots,
      ]);
      $response->addCommand(new MessageCommand($error, '#media-library-messages', ['type' => 'error']));
      return $response;
    }

    return \Drupal::service('media_library.opener_resolver')
      ->get($state)
      ->getSelectionResponse($state$selected_ids)
      

  protected $ajaxResponse;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->ajaxResponse = new AjaxResponse();
  }

  /** * Tests the add and getCommands method. * * @see \Drupal\Core\Ajax\AjaxResponse::addCommand() * @see \Drupal\Core\Ajax\AjaxResponse::getCommands() */
  public function testCommands() {
    $command_one = $this->createMock('Drupal\Core\Ajax\CommandInterface');
    $command_one->expects($this->once())
      
Home | Imprint | This part of the site doesn't use cookies.