ReplaceCommand example

$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;
      }
      else {
        throw new AccessDeniedHttpException();
      }
    }
    else {
      throw new NotFoundHttpException();
    }
  }
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.


    foreach ($updated_rows as $name) {
      foreach ($updated_columns as $key) {
        $element = &$form['fields'][$name][$key];
        $element['#prefix'] = '<div class="ajax-new-content">' . ($element['#prefix'] ?? '');
        $element['#suffix'] = ($element['#suffix'] ?? '') . '</div>';
      }
    }

    // Replace the whole table.     $response->addCommand(new ReplaceCommand('#field-display-overview-wrapper', $form['fields']));

    // Add "row updated" warning after the table has been replaced.     if (!in_array($op['cancel', 'edit'])) {
      foreach ($updated_rows as $name) {
        // The ID of the rendered table row is `$name` processed by getClass().         // @see \Drupal\field_ui\Element\FieldUiTable::tablePreRender         $response->addCommand(new TabledragWarningCommand(Html::getClass($name), 'field-display-overview'));
      }
    }

    return $response;
  }
$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.     if (end($triggering_element['#parents']) === 'remove_button') {
      // When the list of added media is empty, return to the media library and       // shift focus back to the first tabbable element (which should be the       // source field).       if (empty($added_media)) {
        $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this->buildMediaLibraryUi($form_state)));
        $response->addCommand(new FocusFirstCommand('#media-library-add-form-wrapper'));
      }

  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. */
// Announce the updated content to screen readers.     if ($is_remove_button) {
      $media_item = Media::load($field_state['removed_item_id']);
      $announcement = $media_item->access('view label') ? new TranslatableMarkup('@label has been removed.', ['@label' => $media_item->label()]) : new TranslatableMarkup('Media has been removed.');
    }
    else {
      $new_items = count(static::getNewMediaItems($element$form_state));
      $announcement = \Drupal::translation()->formatPlural($new_items, 'Added one media item.', 'Added @count media items.');
    }

    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand("#$wrapper_id", $element));
    $response->addCommand(new AnnounceCommand($announcement));

    // When the remove button is clicked, shift focus to the next remove button.     // When the last item is deleted, we no longer have a selection and shift     // the focus to the open button.     $removed_last = $is_remove_button && !count($field_state['items']);
    if ($is_remove_button && !$removed_last) {
      // Find the next media item by weight. The weight of the removed item is       // added to the field state when it is removed in ::removeItem(). If there       // is no item with a bigger weight, we automatically shift the focus to       // the previous media item.
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 static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {

    // This is used sometimes so let's implode it just once.

  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. */
$this->displayID = $display_id;
    if (!$view->getExecutable()->setDisplay('default')) {
      return;
    }

    // Regenerate the main display area.     $build = $this->getDisplayTab($view);
    $response->addCommand(new HtmlCommand('#views-tab-' . $display_id$build));

    // Regenerate the top area so changes to display names and order will appear.     $build = $this->renderDisplayTop($view);
    $response->addCommand(new ReplaceCommand('#views-display-top', $build));
  }

  /** * Render the top of the display so it can be updated during ajax operations. */
  public function renderDisplayTop(ViewUI $view) {
    $display_id = $this->displayID;
    $element['#theme_wrappers'][] = 'views_ui_container';
    $element['#attributes']['class'] = ['views-display-top', 'clearfix'];
    $element['#attributes']['id'] = ['views-display-top'];

    

  protected function rebuildLayout(SectionStorageInterface $section_storage) {
    $response = new AjaxResponse();
    $layout = [
      '#type' => 'layout_builder',
      '#section_storage' => $section_storage,
    ];
    $response->addCommand(new ReplaceCommand('#layout-builder', $layout));
    return $response;
  }

}
$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 */
    
'command' => 'remove',
      'selector' => '#page-title',
    ];

    $this->assertEquals($expected$command->render());
  }

  /** * @covers \Drupal\Core\Ajax\ReplaceCommand */
  public function testReplaceCommand() {
    $command = new ReplaceCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);

    $expected = [
      'command' => 'insert',
      'method' => 'replaceWith',
      'selector' => '#page-title',
      'data' => '<p>New Text!</p>',
      'settings' => ['my-setting' => 'setting'],
    ];

    $this->assertEquals($expected$command->render());
  }

  
Home | Imprint | This part of the site doesn't use cookies.