О том как заменить стандартную иконку (Throbber) в Drupal 8

Опубликовано admin - пн, 11/09/2020 - 23:23

Для замены стандартной иконки загрузки (Throbber) в Drupal 8 необходимо добавить следующий js код:

(function ($, window, Drupal, drupalSettings) {
  /**
   * Creates a new New progress indicator, which really is full screen.
   */
  Drupal.Ajax.prototype.setProgressIndicatorNew = function () {
    this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen ajax-progress-new">&nbsp;</div>');
    // My theme has a wrapping element that will match #main.
    
    $('body').append(this.progress.element);
  };


  // Override the progress throbber, to actually use a different progress style
  // if the element had something specified.
  var originalThrobber = Drupal.Ajax.prototype.setProgressIndicatorThrobber;
  Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
    var $target = $(this.element);
    var progress = $target.data('progressType') || 'throbber';

    if (progress === 'throbber') {
      originalThrobber.call(this);
    }
    else {
      var progressIndicatorMethod = 'setProgressIndicator' + progress.slice(0, 1).toUpperCase() + progress.slice(1).toLowerCase();
      if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
        this[progressIndicatorMethod].call(this);
      }
    }
  };
})(jQuery, window, Drupal, drupalSettings);

В данном случае имя нового прогрессбара "New", указанный код я разместил в директории js/ajax-overrides.js. Разберем его.

Для начала нам понадобится создать сам индикатор:

 Drupal.Ajax.prototype.setProgressIndicatorNew = function () {
    this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen ajax-progress-new">&nbsp;</div>');

В остальном коде мы заменяем стандартный прогрессбар, если в свойствах имеется аттрибут (data-dialog-type) отличный от throbber:

  // Override the progress throbber, to actually use a different progress style
  // if the element had something specified.
  var originalThrobber = Drupal.Ajax.prototype.setProgressIndicatorThrobber;
  Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
    var $target = $(this.element);
    var progress = $target.data('progressType') || 'throbber';

    if (progress === 'throbber') {
      originalThrobber.call(this);
    }
    else {
      var progressIndicatorMethod = 'setProgressIndicator' + progress.slice(0, 1).toUpperCase() + progress.slice(1).toLowerCase();
      if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
        this[progressIndicatorMethod].call(this);
      }
    }
  };

примерный код элемента ссылки:

    $form['open_modal'] = [
      '#type' => 'link',
      '#title' => $this->t('Open Modal'),
      '#url' => Url::fromRoute('my_module.open_modal_form'),

      '#options' => [

        'attributes' => [
          'data-ajax-progress' => 'fullscreen',
          'data-progress-type' => 'new',
          'class' => ['use-ajax','front-modal'],
          'data-dialog-type' => ['modal'],
          //'data-dialog-renderer'=>["off_canvas"],
          'data-dialog-options' => Json::encode([
            'width' => '1200',
            'effect' => 'fade',
            'autoResize'=>false
          ]),
          'style' => [

            'display:none;',
          ],

        ],

Таким образом у вас будет свой html код замещающий стандартный:

<div class="ajax-progress ajax-progress-fullscreen ajax-progress-new">&nbsp;</div>'

А дальше дело за малым...

Сам css стиль класс "ajax-progress-fullscreen" находится здесь core/modules/system/css/components/ajax-progress.module.css:

/* Full screen throbber */
.ajax-progress-fullscreen {
  position: fixed;
  z-index: 1000;
  top: 48.5%;
  /* Can't do center:50% middle: 50%, so approximate it for a typical window size. */
  left: 49%; /* LTR */
  width: 24px;
  height: 24px;
  padding: 4px;
  opacity: 0.9;
  border-radius: 7px;
  background-color: #232323;
  background-image: url(../../../../misc/loading-small.gif);
  background-repeat: no-repeat;
  background-position: center center;
}

 

Взаимосвязанные материалы

# 1. О том как заменить стандартную иконку (Throbber) в Drupal 8 (понедельник, ноября 9, 2020 - 23:23 ),

Для замены стандартной иконки загрузки (Throbber) в Drupal 8 необходимо добавить следующий js код:

читать...
# 2. SetHandler none Drupal_Security...... (вторник, октября 6, 2020 - 23:26 ),
Долго пришлось искать проблему не отображения файлов для которых созданы стили в Drupal 8. читать...
# 3. Temporary file '*****.tmp' could not be created (суббота, сентября 26, 2020 - 19:37 ),

Если в последних версиях Drupal 8 появилась ошибка "Temporary file '*****.tmp' could not be created"

необходимо добавить в  файл \sites\default\settings.php  строку

читать...
# 4. Как правильно кэшировать хлебные крошки в Drupal 8 (среда, января 29, 2020 - 14:12 ),

Несколько раз сталкивался с тем что последний элемент Breadcrumb кэшировался на страницах с типом "node", несмотря на то, что страница менялась. То же самое наблюдалось и с view. читать...

# 5. Drupal 8. Несколько способов вывода информации черех Ajax (понедельник, января 27, 2020 - 23:23 ),
О том, как осуществить вывод информации с использованием ajax в Drupal 8. В Drupal 8 имеется несколько методов вывода информации через ajax - c применением методов Api и с использованием стандартных функций jQuery. При этом jQuery в Drupal 8 установлена по умолчанию. читать...
На разработку сайта! Скидки до 20%!