To run a behavior after an Ajax call you need to call once it stops

23rd Jun 2022
Table of contents
Drupal.behaviors.enableOnChrome = {
  attach: function(context, settings) {
    // Add class for chrome tiles.
    $(context).ajaxStop(function () {
      $(this).find('.Chromebook').each(function() {
        $(this).closest('.slide__grid', context).addClass('chrome');
      });
    });
  }
};

By using this code in my site the class is set the first time, but after a ajax call it's not, what is wrong?

(function ($, Drupal, drupalSettings) {
  'use strict';

  Drupal.behaviors.enableOnChrome = {
    attach: function(context, settings) {

      // Add class for chrome tiles.
      
    $(context).find('.Chromebook').once('.grid__content').each(function() {
        $(this).closest('.slide__grid', context).addClass('chrome');
      });
   
    }
  };
}) (jQuery, Drupal, drupalSettings);

AjaxResponse::addCommand Examples

No.1

/**
   * Calls a method on an entity queue and reloads the listing page.
   *
   * @param \Drupal\entityqueue\EntityQueueInterface $entity_queue
   *   The view being acted upon.
   * @param string $op
   *   The operation to perform, e.g., 'enable' or 'disable'.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Either returns a rebuilt listing page as an AJAX response, or redirects
   *   back to the listing page.
   */
  public function ajaxOperation(EntityQueueInterface $entity_queue, $op, Request $request) {
    // Perform the operation.
    $entity_queue->$op()->save();

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

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

No. 2

/**
  * Ajax callback to validate the email field.
  */
 public function submitEmailAjax(array &$form, FormStateInterface $form_state)
 {
     $valid = $this->validateEmail($form, $form_state);
     $response = new AjaxResponse();
     if ($valid) {
         $css = ['border' => '1px solid green'];
         $message = $this->t('Email ok.');
     } else {
         $css = ['border' => '1px solid red'];
         $message = $this->t('Email not valid.');
     }
     // $response->addCommand(new CssCommand('#edit-email', $css));.
     $response->addCommand(new OpenModalDialogCommand('Alert', 'hello', array('width' => '700')));
     return $response;
 }

No. 3

/**
  * Ajax callback to render a sample of the input date format.
  *
  * @param array $form
  *   Form API array structure.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Form state information.
  *
  * @return AjaxResponse
  *   Ajax response with the rendered sample date using the given format. If
  *   the given format cannot be identified or was empty, the response will
  *   be empty as well.
  */
 public static function ajaxSample(array $form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     $format_value = NestedArray::getValue($form_state->getValues(), $form_state->getTriggeringElement()['#array_parents']);
     if (!empty($format_value)) {
         // Format the date with a custom date format with the given pattern.
         // The object is not instantiated in an Ajax context, so $this->t()
         // cannot be used here.
         $format = t('Displayed as %date_format', array('%date_format' => \Drupal::service('date.formatter')->format(REQUEST_TIME, 'custom', $format_value)));
         // Return a command instead of a string, since the Ajax framework
         // automatically prepends an additional empty DIV element for a string,
         // which breaks the layout.
         $response->addCommand(new ReplaceCommand('#edit-date-format-suffix', '<small id="edit-date-format-suffix">' . $format . '</small>'));
     }
     return $response;
 }

No. 4

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

No. 5

 /**
  * Ajax callback triggered by checkbox.
  */
 function checkboxCallback($form, $form_state)
 {
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax_checkbox_value', (int) $form_state['values']['checkbox']));
     $response->addCommand(new DataCommand('#ajax_checkbox_value', 'form_state_value_select', (int) $form_state['values']['checkbox']));
     return $response;
 }

No. 6

/**
  * {@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.';
             }
             $response->addCommand(new AlertCommand($error));
         }
     }
     $html = $this->drupalRenderRoot($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 = array('#type' => 'status_messages');
     $output = $this->drupalRenderRoot($status_messages);
     if (!empty($output)) {
         $response->addCommand(new PrependCommand(NULL, $output));
     }
     return $response;
 }

No. 7

/**
  * Tests the add and getCommands method.
  *
  * @see \Drupal\Core\Ajax\AjaxResponse::addCommand()
  * @see \Drupal\Core\Ajax\AjaxResponse::getCommands()
  */
 public function testCommands()
 {
     $command_one = $this->getMock('Drupal\\Core\\Ajax\\CommandInterface');
     $command_one->expects($this->once())->method('render')->will($this->returnValue(array('command' => 'one')));
     $command_two = $this->getMock('Drupal\\Core\\Ajax\\CommandInterface');
     $command_two->expects($this->once())->method('render')->will($this->returnValue(array('command' => 'two')));
     $command_three = $this->getMock('Drupal\\Core\\Ajax\\CommandInterface');
     $command_three->expects($this->once())->method('render')->will($this->returnValue(array('command' => 'three')));
     $this->ajaxResponse->addCommand($command_one);
     $this->ajaxResponse->addCommand($command_two);
     $this->ajaxResponse->addCommand($command_three, TRUE);
     // Ensure that the added commands are in the right order.
     $commands =& $this->ajaxResponse->getCommands();
     $this->assertSame($commands[1], array('command' => 'one'));
     $this->assertSame($commands[2], array('command' => 'two'));
     $this->assertSame($commands[0], array('command' => 'three'));
     // Remove one and change one element from commands and ensure the reference
     // worked as expected.
     unset($commands[2]);
     $commands[0]['class'] = 'test-class';
     $commands = $this->ajaxResponse->getCommands();
     $this->assertSame($commands[1], array('command' => 'one'));
     $this->assertFalse(isset($commands[2]));
     $this->assertSame($commands[0], array('command' => 'three', 'class' => 'test-class'));
 }

No. 8

public function ajaxSubmit(array &$form, FormStateInterface $form_state)
 {
     //---------------------------------------------------------------
     //            get the own attributes values of the swap
     //---------------------------------------------------------------
     //get all the swaps plugins
     $manager = \Drupal::service('plugin.manager.swaps');
     $swaps = $manager->getDefinitions();
     $swap = $swaps['column'];
     $input = $form_state->getUserInput();
     $settings = array();
     $settings['size'] = $input['swaps_column_size'];
     $settings['number'] = $input['swaps_column_number'];
     //---------------------------------------------------------------
     // get the default attributes values of the swap (required for visual help)
     //---------------------------------------------------------------
     $settings['swapId'] = $swap['id'];
     $settings['swapName'] = $swap['name'];
     $settings['container'] = $swap['container'];
     SwapDefaultAttributes::getDefaultFormElementsValues($settings, $input);
     //---------------------------------------------------------------
     //            create the ajax response
     //---------------------------------------------------------------
     $visualSettings = array('visualContentLayout' => array('attributes' => $settings));
     $response = new AjaxResponse();
     $response->addCommand(new CloseModalDialogCommand());
     $response->addCommand(new SettingsCommand($visualSettings, FALSE));
     return $response;
 }

No. 9

public function validateEmailAjax(array &$form, FormStateInterface $form_state)
 {
     $httpClient = \Drupal::httpClient();
     $configuration = $this->config('gestiondenuncias.configuration');
     $pwd = $configuration->get('contrasena_verifyemail');
     $usr = $configuration->get('nombre_ususario_verifyemail');
     $email = $form_state->getValues('denunciante')['email'];
     $serverResponse = json_decode($httpClient->request('POST', "http://api.verify-email.org/api.php?usr={$usr}&pwd={$pwd}&check={$email}")->getBody()->getContents());
     $response = new AjaxResponse();
     if ($serverResponse->authentication_status != 1) {
         \Drupal::logger('gestiondenuncias.verify-email')->error('Los parametros de conexion a verify-email son incorrectos');
     } else {
         if ($serverResponse->limit_status) {
             \Drupal::logger('gestiondenuncias.verify-email')->error('Se llego al limite de consultas de verify-email');
         } else {
             if ($serverResponse->verify_status) {
                 $css = ['border' => '1px solid green'];
                 $message = $this->t('Email válido');
             } else {
                 $css = ['border' => '1px solid red'];
                 $message = $this->t('Email parece ser inválido');
             }
             $message = $message . $form_state->getValues()['denunciante']['email'];
             $response->addCommand(new CssCommand('#edit-email', $css));
             $response->addCommand(new HtmlCommand('.email-valid-message', $message));
         }
     }
     return $response;
 }

No. 10

 public function ajaxFormCallback(array &$form, FormStateInterface $form_state)
 {
     dd('callback');
     //dd(array_keys($form['ajax_wrapper']));
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax_wrapper', $form['ajax_wrapper']));
     $status_messages = ['#type' => 'status_messages'];
     $response->addCommand(new HtmlCommand('.highlighted aside .region', $status_messages));
     return $response;
 }

No. 11

 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $form));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }

No. 12

/**
  * Processes AJAX file uploads and deletions.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   An AjaxResponse object.
  */
 public function upload(Request $request)
 {
     $form_parents = explode('/', $request->query->get('element_parents'));
     $form_build_id = $request->query->get('form_build_id');
     $request_form_build_id = $request->request->get('form_build_id');
     if (empty($request_form_build_id) || $form_build_id !== $request_form_build_id) {
         // Invalid request.
         drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
         $response = new AjaxResponse();
         $status_messages = array('#theme' => 'status_messages');
         return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages)));
     }
     try {
         /** @var $ajaxForm \Drupal\system\FileAjaxForm */
         $ajaxForm = $this->getForm($request);
         $form = $ajaxForm->getForm();
         $form_state = $ajaxForm->getFormState();
         $commands = $ajaxForm->getCommands();
     } catch (HttpExceptionInterface $e) {
         // Invalid form_build_id.
         drupal_set_message(t('An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.'), 'error');
         $response = new AjaxResponse();
         $status_messages = array('#theme' => 'status_messages');
         return $response->addCommand(new ReplaceCommand(NULL, drupal_render($status_messages)));
     }
     // Get the current element and count the number of files.
     $current_element = NestedArray::getValue($form, $form_parents);
     $current_file_count = isset($current_element['#file_upload_delta']) ? $current_element['#file_upload_delta'] : 0;
     // Process user input. $form and $form_state are modified in the process.
     drupal_process_form($form['#form_id'], $form, $form_state);
     // Retrieve the element to be rendered.
     $form = NestedArray::getValue($form, $form_parents);
     // Add the special Ajax class if a new file was added.
     if (isset($form['#file_upload_delta']) && $current_file_count < $form['#file_upload_delta']) {
         $form[$current_file_count]['#attributes']['class'][] = 'ajax-new-content';
     } else {
         $form['#suffix'] .= '<span class="ajax-new-content"></span>';
     }
     $status_messages = array('#theme' => 'status_messages');
     $form['#prefix'] .= drupal_render($status_messages);
     $output = drupal_render($form);
     drupal_process_attached($form);
     $js = _drupal_add_js();
     $settings = drupal_merge_js_settings($js['settings']['data']);
     $response = new AjaxResponse();
     foreach ($commands as $command) {
         $response->addCommand($command, TRUE);
     }
     return $response->addCommand(new ReplaceCommand(NULL, $output, $settings));
 }

No. 14

/**
  * 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 = ajax_test_dialog_contents();
     $response = new AjaxResponse();
     $title = $this->t('AJAX Dialog contents');
     $html = drupal_render($content);
     if ($is_modal) {
         $response->addCommand(new OpenModalDialogCommand($title, $html));
     } else {
         $selector = '#ajax-test-dialog-wrapper-1';
         $response->addCommand(new OpenDialogCommand($selector, $title, $html));
     }
     return $response;
 }

No. 15

 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix'], $form['#suffix']);
         $status_messages = array('#theme' => 'status_messages');
         $output = drupal_render($form);
         $output = '<div>' . drupal_render($status_messages) . $output . '</div>';
         $response->addCommand(new HtmlCommand('#editor-link-dialog-form', $output));
     } else {
         $response->addCommand(new EditorDialogSave($form_state->getValues()));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }

No. 16

/**
  * 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';
         $response->addCommand(new OpenDialogCommand($selector, $title, $content));
     }
     return $response;
 }

No. 17

 /**
  * AJAX callback.
  */
 public function ajaxCallback($form, FormStateInterface $form_state)
 {
     $item = ['#type' => 'item', '#title' => $this->t('Ajax value'), '#markup' => microtime()];
     $response = new AjaxResponse();
     $response->addCommand(new HtmlCommand('#ajax-value', $item));
     return $response;
 }

No. 18

 /**
  * Catches a form AJAX exception and build a response from it.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event
  *   The event to process.
  */
 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);
         }
     }
 }

No. 19

/**
  * Returns an Ajax response to render a text field without transformation filters.
  *
  * @param \Drupal\Core\Entity\EntityInterface $entity
  *   The entity of which a formatted text field is being rerendered.
  * @param string $field_name
  *   The name of the (formatted text) field that that is being rerendered
  * @param string $langcode
  *   The name of the language for which the formatted text field is being
  *   rerendered.
  * @param string $view_mode_id
  *   The view mode the formatted text field should be rerendered in.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   The Ajax response.
  */
 public function getUntransformedText(EntityInterface $entity, $field_name, $langcode, $view_mode_id)
 {
     $response = new AjaxResponse();
     // Direct text editing is only supported for single-valued fields.
     $field = $entity->getTranslation($langcode)->{$field_name};
     $editable_text = check_markup($field->value, $field->format, $langcode, array(FilterInterface::TYPE_TRANSFORM_REVERSIBLE, FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE));
     $response->addCommand(new GetUntransformedTextCommand($editable_text));
     return $response;
 }

No. 20

 public function addEmailCallback(array &$form, FormStateInterface $form_state)
 {
     $email = $form_state->getValue('new_email');
     if (\Drupal::service('email.validator')->isValid($email)) {
         $config = \Drupal::service('config.factory')->getEditable('registration_role_with_approval.settings');
         $mailing_list = $config->get('mailing_list');
         $mailing_list .= " " . $email;
         $config->set('mailing_list', $mailing_list);
         $config->save();
         $form['custom_mail']['mailing_list']['#default_value'] = $mailing_list;
         $ajax_response = new AjaxResponse();
         $ajax_response->addCommand(new InvokeCommand('#edit-mailing-list', 'val', $mailing_list));
         $ajax_response->addCommand(new ChangedCommand('#edit-mailing-list', '#edit-mailing-list'));
         $ajax_response->addCommand(new InvokeCommand('#edit-mailing-list', 'change'));
         //return $form['custom_mail']['mailing_list'];
         return $ajax_response;
     }
 }

No. 21

/**
  * Custom ajax form submission handler.
  *
  * @param array $form
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  */
 public function add(array &$form, FormStateInterface $form_state)
 {
     $context = $form_state->getValue('contexts');
     $content = \Drupal::formBuilder()->getForm($this->getContextClass(), $context, $this->getTempstoreId(), $this->machine_name);
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response = new AjaxResponse();
     $response->addCommand(new OpenModalDialogCommand($this->t('Configure Required Context'), $content, array('width' => '700')));
     return $response;
 }

No. 22

/**
  * Returns an Ajax response to generate preview of embedded items.
  *
  * Expects the the HTML element as GET parameter.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request object.
  * @param \Drupal\filter\FilterFormatInterface $filter_format
  *   The filter format.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *   Throws an exception if 'value' parameter is not found in the request.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   The preview of the embedded item specified by the data attributes.
  */
 public function preview(Request $request, FilterFormatInterface $filter_format)
 {
     $text = $request->get('value');
     if ($text == '') {
         throw new NotFoundHttpException();
     }
     $output = check_markup($text, $filter_format->id());
     $response = new AjaxResponse();
     $response->addCommand(new EmbedInsertCommand($output));
     return $response;
 }

No. 23

 /**
  * Returns an node through JSON.
  *
  * @param Request $request
  *  The global request object.
  * @param string $entityType
  *  The type of the requested entity.
  * @param string $entityId
  *  The id of the requested entity.
  * @param string $viewMode
  *  The view mode you wish to render for the requested entity.
  *
  * @return array
  *   The Views fields report page.
  */
 public function switchViewMode(Request $request, $entityType, $entityId, $viewMode)
 {
     $response = new AjaxResponse();
     $entity = entity_load($entityType, $entityId);
     if ($entity->access('view')) {
         $element = entity_view($entity, $viewMode);
         $content = \Drupal::service('renderer')->render($element, FALSE);
         $response->addCommand(new ReplaceCommand('.' . $request->get('selector'), $content));
     }
     return $response;
 }

No. 24

public function add(array &$form, FormStateInterface $form_state)
 {
     $condition = $form_state->getValue('conditions');
     $content = \Drupal::formBuilder()->getForm($this->getConditionClass(), $condition, $this->getTempstoreId(), $this->machine_name);
     $content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     list(, $route_parameters) = $this->getOperationsRouteInfo($this->machine_name, $form_state->getValue('conditions'));
     $content['submit']['#attached']['drupalSettings']['ajax'][$content['submit']['#id']]['url'] = $this->url($this->getAddRoute(), $route_parameters, ['query' => [FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]]);
     $response = new AjaxResponse();
     $response->addCommand(new OpenModalDialogCommand($this->t('Configure Required Context'), $content, array('width' => '700')));
     return $response;
 }

No. 25

 /**
  * Implements the sumbit handler for the ajax call.
  *
  * @param array $form
  *   Render array representing from.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   Current form state.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   Array of ajax commands to execute on submit of the modal form.
  */
 public function ajaxSubmitForm(array &$form, FormStateInterface $form_state)
 {
     // At this point the submit handler has fired.
     // Clear the message set by the submit handler.
     drupal_get_messages();
     // We begin building a new ajax reponse.
     $response = new AjaxResponse();
     if ($form_state->getErrors()) {
         unset($form['#prefix']);
         unset($form['#suffix']);
         $form['status_messages'] = ['#type' => 'status_messages', '#weight' => -10];
         $response->addCommand(new HtmlCommand('#fapi-example-modal-form', $form));
     } else {
         $title = $form_state->getValue('title');
         $message = t('You specified a title of %title.', ['%title' => $title]);
         $content = ['#type' => 'html_tag', '#tag' => 'p', '#value' => $message];
         $response->addCommand(new HtmlCommand('#fapi-example-message', $content));
         $response->addCommand(new CloseModalDialogCommand());
     }
     return $response;
 }

No. 26

/**
  * Converts the output of a controller into an Ajax response object.
  *
  * @var mixed $content
  *   The return value of a controller, for example a string, a render array, a
  *   HtmlFragment object, a Response object or even an AjaxResponse itself.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  *   An Ajax response containing the controller result.
  */
 public function render($content)
 {
     // If there is already a Response object, return it without manipulation.
     if ($content instanceof Response && $content->isOk()) {
         return $content;
     }
     // Allow controllers to return an HtmlFragment directly.
     if ($content instanceof HtmlFragment) {
         $content = $content->getContent();
     }
     // Most controllers return a render array, but some return a string.
     if (!is_array($content)) {
         $content = array('#markup' => $content);
     }
     $response = new AjaxResponse();
     if (isset($content['#type']) && $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.
         $content += $this->elementInfo('ajax');
         $error = $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->drupalRender($content);
     // 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 = array('#theme' => 'status_messages');
     $output = $this->drupalRender($status_messages);
     if (!empty($output)) {
         $response->addCommand(new PrependCommand(NULL, $output));
     }
     return $response;
 }

No. 27

function er_browser_widget_search_content(array &$form, FormStateInterface $form_state)
 {
     $form = \Drupal::formBuilder()->getForm('Drupal\\er_browser_widget\\Form\\EntityReferenceBrowserWidgetForm');
     $response = new AjaxResponse();
     $title = $this->t('Entity Search and Reference.');
     $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response->setAttachments($form['#attached']);
     $content = views_embed_view('entity_reference_browser_widget');
     $options = array('dialogClass' => 'test-dialog', 'width' => '75%');
     $modal = new OpenModalDialogCommand($title, $form, $options);
     $response->addCommand($modal);
     return $response;
 }

No. 28

/**
  * Assign this task to the current user and reloads the listing page.
  *
  * @param \Drupal\tmgmt_local\LocalTaskInterface $tmgmt_local_task
  *   The task being acted upon.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
  *   Either returns a rebuilt listing page as an AJAX response, or redirects
  *   back to the listing page.
  */
 public function assignToMe(LocalTaskInterface $tmgmt_local_task, Request $request)
 {
     $tmgmt_local_task->assign(\Drupal::currentUser());
     $tmgmt_local_task->save();
     drupal_set_message(t('The task has been assigned to you.'));
     // 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('<current>');
 }

No. 29

/**
  * Returns an AJAX response to render the toolbar subtrees.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse
  */
 public function subtreesAjax()
 {
     list($subtrees, $cacheability) = 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);
     $response->setExpires($expires);
     return $response;
 }

No. 30

/**
  * {@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'][] = 'outside_in/drupal.off_canvas';
     $response->setAttachments($main_content['#attached']);
     // If the main content doesn't provide a title, use the title resolver.
     $title = isset($main_content['#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->get('dialogOptions', []);
     $response->addCommand(new OpenOffCanvasDialogCommand($title, $content, $options));
     return $response;
 }

No. 31

/**
  * {@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 = drupal_render_root($main_content);
     // Attach the library necessary for using the OpenDialogCommand and set the
     // attachments for this Ajax response.
     $main_content['#attached']['library'][] = 'core/drupal.dialog.ajax';
     $response->setAttachments($main_content['#attached']);
     // Determine the title: use the title provided by the main content if any,
     // otherwise get it from the routing information.
     $title = isset($main_content['#title']) ? $main_content['#title'] : $this->titleResolver->getTitle($request, $route_match->getRouteObject());
     // Determine the dialog options and the target for the OpenDialogCommand.
     $options = $request->request->get('dialogOptions', array());
     $target = $this->determineTargetSelector($options, $route_match);
     $response->addCommand(new OpenDialogCommand($target, $title, $content, $options));
     return $response;
 }
Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.