Skip to main content
edited tags
Link
avpaderno
  • 97.9k
  • 15
  • 164
  • 284
Source Link
usernameabc
  • 2.8k
  • 5
  • 48
  • 98

How to add library if Ajax is enabled for view?

We have a view, myview, where Ajax is disabled. We created a custom library that would override the load more button's indicator so that we can use our own. However, we would only like to add this library conditionally if myviews->Use Ajax->Enabled, but when it is disabled then do not add the library. I know how to conditionally add the library, but not sure how to check if myviews->Use Ajax is set to enabled.

How can we detect if myview->Use Ajax->enabled?

mytheme.libraries.yml

mytheme-custom-indicator:
  version: 1.0
  js:
    /path/to/js/custom-indicator.js: { attributes: { defer: true }}
  dependencies:
    - core/drupal
    - core/drupal.ajax
    - core/jquery

custom-indicator.js

 /**
   * Infinite scrolling progress indicator.
   *
   * @type {{attach: Drupal.behaviors.progressIndicator.attach}}
   */
  Drupal.behaviors.progressIndicator = {
    attach: function (context, settings) {
      Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
        this.progress.element = $('<div class="myclass"> </div>');
        $('body .pager').after(this.progress.element);
      };
    }
  };

What we tried

/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
}

Goal

/**
 * Implements hook_views_pre_render().
 */
function ns_general_views_pre_render(ViewExecutable $view) {
  // Add library to all for ajax progress.
  if($view->hasAjax) {
    $view->element['#attached']['library'][] = 'mytheme/mytheme-custom-indicator';
  }
}