addCommand example

    // attribute.     if (!empty($form_state->get('filter_default_view_mode')) && $form_state->getValue(['attributes', 'data-view-mode']) === $form_state->get('filter_default_view_mode')) {
      $form_state->setValue(['attributes', 'data-view-mode'], FALSE);
    }

    if ($form_state->getErrors()) {
      unset($form['#prefix']$form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response->addCommand(new HtmlCommand('#editor-media-dialog-form', $form));
    }
    else {
      // Only send back the relevant values.       $values = [
        'hasCaption' => $form_state->getValue('hasCaption'),
        'attributes' => $form_state->getValue('attributes'),
      ];
      $response->addCommand(new EditorDialogSave($values));
      $response->addCommand(new CloseModalDialogCommand());
    }

    

class ToolbarController extends ControllerBase implements TrustedCallbackInterface {

  /** * Returns an AJAX response to render the toolbar subtrees. * * @return \Drupal\Core\Ajax\AjaxResponse */
  public function subtreesAjax() {
    [$subtrees] = toolbar_get_rendered_subtrees();
    $response = new AjaxResponse();
    $response->addCommand(new SetSubtreesCommand($subtrees));

    // The Expires HTTP header is the heart of the client-side HTTP caching. The     // additional server-side page cache only takes effect when the client     // accesses the callback URL again (e.g., after clearing the browser cache     // or when force-reloading a Drupal page).     $max_age = 365 * 24 * 60 * 60;
    $response->setPrivate();
    $response->setMaxAge($max_age);

    $expires = new \DateTime();
    $expires->setTimestamp(REQUEST_TIME + $max_age);
    
// Override width option.     switch ($this->mode) {
      case 'wide':
        $options['width'] = 700;
        break;

      case 'extra_wide':
        $options['width'] = 1000;
        break;
    }

    $response->addCommand(new OpenModalDialogCommand($title$content$options));
    return $response;
  }

}
continue;
        }
      }

      // Create a new AjaxResponse.       $ajax_response = new AjaxResponse();
      // JavaScript's querySelector automatically decodes HTML entities in       // attributes, so we must decode the entities of the current BigPipe       // placeholder ID (which has HTML entities encoded since we use it to find       // the placeholders).       $big_pipe_js_placeholder_id = Html::decodeEntities($placeholder_id);
      $ajax_response->addCommand(new ReplaceCommand(sprintf('[data-big-pipe-placeholder-id="%s"]', $big_pipe_js_placeholder_id)$elements['#markup']));
      $ajax_response->setAttachments($elements['#attached']);

      // Push a fake request with the asset libraries loaded so far and dispatch       // KernelEvents::RESPONSE event. This results in the attachments for the       // AJAX response being processed by AjaxResponseAttachmentsProcessor and       // hence:       // - the necessary AJAX commands to load the necessary missing asset       // libraries and updated AJAX page state are added to the AJAX response       // - the attachments associated with the response are finalized, which       // allows us to track the total set of asset libraries sent in the       // initial HTML response plus all embedded AJAX responses sent so far.
        $origin_destination = $request_clone->getBasePath() . '/' . ltrim($path ?? '/', '/');

        $used_query_parameters = $request_clone->query->all();
        $query = UrlHelper::buildQuery($used_query_parameters);
        if ($query != '') {
          $origin_destination .= '?' . $query;
        }
        $this->redirectDestination->set($origin_destination);

        // Override the display's pager_element with the one actually used.         if (isset($pager_element)) {
          $response->addCommand(new ScrollTopCommand(".js-view-dom-id-$dom_id"));
          $view->displayHandlers->get($display_id)->setOption('pager_element', $pager_element);
        }
        // Reuse the same DOM id so it matches that in drupalSettings.         $view->dom_id = $dom_id;

        $preview = $view->preview($display_id$args);
        $response->addCommand(new ReplaceCommand(".js-view-dom-id-$dom_id", $preview));
        $response->addCommand(new PrependCommand(".js-view-dom-id-$dom_id", ['#type' => 'status_messages']));

        return $response;
      }
      

  public function ajaxOperation(ViewEntityInterface $view$op, Request $request) {
    // Perform the operation.     $view->$op()->save();

    // If the request is via AJAX, return the rendered list as JSON.     if ($request->request->get('js')) {
      $list = $this->entityTypeManager()->getListBuilder('view')->render();
      $response = new AjaxResponse();
      $response->addCommand(new ReplaceCommand('#views-entity-list', $list));
      return $response;
    }

    // Otherwise, redirect back to the page.     return $this->redirect('entity.view.collection');
  }

  /** * Menu callback for Views tag autocompletion. * * Like other autocomplete functions, this function inspects the 'q' query * parameter for the string to use to search for suggestions. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A JSON response containing the autocomplete suggestions for Views tags. */
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.';
        }
        $response->addCommand(new AlertCommand($error));
      }
    }

    $html = $this->renderer->renderRoot($main_content);
    $response->setAttachments($main_content['#attached']);

    // The selector for the insert command is NULL as the new content will     // replace the element making the Ajax call. The default 'replaceWith'     // behavior can be changed with #ajax['method'].     $response->addCommand(new InsertCommand(NULL, $html));
    $status_messages = ['#type' => 'status_messages'];
    

  protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state) {
    if ($redirect_url = $this->getRedirectUrl()) {
      $command = new RedirectCommand($redirect_url->setAbsolute()->toString());
    }
    else {
      // Settings Tray always provides a destination.       throw new \Exception("No destination provided by Settings Tray form");
    }
    $response = new AjaxResponse();
    return $response->addCommand($command);
  }

  /** * Gets the form's redirect URL from 'destination' provide in the request. * * @return \Drupal\Core\Url|null * The redirect URL or NULL if dialog should just be closed. */
  protected function getRedirectUrl() {
    // \Drupal\Core\Routing\RedirectDestination::get() cannot be used directly     // because it will use <current> if 'destination' is not in the query

      $form_state->set('url', $form_url);
      $response = $this->ajaxFormWrapper($form_class$form_state);
    }
    elseif (!$form_state->get('ajax')) {
      // if nothing on the stack, non-js forms just go back to the main view editor.       $display_id = $form_state->get('display_id');
      return new RedirectResponse(Url::fromRoute('entity.view.edit_display_form', ['view' => $view->id(), 'display_id' => $display_id]['absolute' => TRUE])->toString());
    }
    else {
      $response = new AjaxResponse();
      $response->addCommand(new CloseModalDialogCommand());
      $response->addCommand(new ShowButtonsCommand(!empty($view->changed)));
      $response->addCommand(new TriggerPreviewCommand());
      if ($page_title = $form_state->get('page_title')) {
        $response->addCommand(new ReplaceTitleCommand($page_title));
      }
    }
    // If this form was for view-wide changes, there's no need to regenerate     // the display section of the form.     if ($display_id !== '') {
      \Drupal::entityTypeManager()->getFormObject('view', 'edit')->rebuildCurrentTab($view$response$display_id);
    }

    
    // 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());

    // Determine the title: use the title provided by the main content if any,     // otherwise get it from the routing information.     $options = $request->request->all('dialogOptions');

    $response->addCommand(new OpenModalDialogCommand($title$content$options));
    return $response;
  }

}

  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    if ($form_state->hasAnyErrors()) {
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -1000,
      ];
      $form['#sorted'] = FALSE;
      $response = new AjaxResponse();
      $response->addCommand(new ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
    }
    else {
      $response = $this->successfulAjaxSubmit($form$form_state);
    }
    return $response;
  }

  /** * Allows the form to respond to a successful AJAX submission. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @return \Drupal\Core\Ajax\AjaxResponse * An AJAX response. */
    $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)
      ->addCommand(new CloseDialogCommand());
  }

  /** * {@inheritdoc} */

  protected function rebuildAndClose(SectionStorageInterface $section_storage) {
    $response = $this->rebuildLayout($section_storage);
    $response->addCommand(new CloseDialogCommand('#drupal-off-canvas'));
    return $response;
  }

  /** * Rebuilds the layout. * * @param \Drupal\layout_builder\SectionStorageInterface $section_storage * The section storage. * * @return \Drupal\Core\Ajax\AjaxResponse * An AJAX response to either rebuild the layout and close the dialog, or * reload the page. */
/** * 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');
    $response->addCommand(new HtmlCommand('#ajax_date_value', sprintf('<div>%s</div>', $date)));
    
$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.     /** @var \Drupal\media\MediaSourceInterface $source */
    
Home | Imprint | This part of the site doesn't use cookies.