You are here

function _webform_page_attachments in Webform 6.x

Same name and namespace in other branches
  1. 8.5 webform.module \_webform_page_attachments()

Add webform libraries to page attachments.

Parameters

array $attachments: An array of page attachments.

2 calls to _webform_page_attachments()
webform_form_alter in includes/webform.form_alter.inc
Implements hook_form_alter().
webform_page_attachments in ./webform.module
Implements hook_page_attachments().

File

./webform.module, line 601
Enables the creation of webforms and questionnaires.

Code

function _webform_page_attachments(array &$attachments) {

  // Attach webform theme specific libraries.

  /** @var \Drupal\webform\WebformThemeManagerInterface $theme_manager */
  $theme_manager = \Drupal::service('webform.theme_manager');
  $active_theme_names = $theme_manager
    ->getActiveThemeNames();
  foreach ($active_theme_names as $active_theme_name) {
    if (file_exists(drupal_get_path('module', 'webform') . "/css/webform.theme.{$active_theme_name}.css")) {
      $attachments['#attached']['library'][] = "webform/webform.theme.{$active_theme_name}";
    }
  }

  // Attach webform contextual link helper.
  if (\Drupal::currentUser()
    ->hasPermission('access contextual links')) {
    $attachments['#attached']['library'][] = 'webform/webform.contextual';
  }

  // Attach details element save open/close library.
  // This ensures pages without a webform will still be able to save the
  // details element state.
  if (\Drupal::config('webform.settings')
    ->get('ui.details_save')) {
    $attachments['#attached']['library'][] = 'webform/webform.element.details.save';
  }

  // Add 'info' message style to all webform pages.
  $attachments['#attached']['library'][] = 'webform/webform.element.message';

  // Get current webform, if it does not exist exit.

  /** @var \Drupal\webform\WebformRequestInterface $request_handler */
  $request_handler = \Drupal::service('webform.request');
  $webform = $request_handler
    ->getCurrentWebform();
  if (!$webform) {
    return;
  }

  // Assets: Add custom shared and webform specific CSS and JS.
  // @see webform_library_info_build()
  $assets = $webform
    ->getAssets();
  foreach ($assets as $type => $value) {
    if ($value) {
      $attachments['#attached']['library'][] = 'webform/webform.' . $type . '.' . $webform
        ->id();
    }
  }

  // Attach variant randomization JavaScript.
  $route_name = \Drupal::routeMatch()
    ->getRouteName();
  $route_names = [
    'entity.webform.canonical',
    'entity.webform.test_form',
    'entity.node.canonical',
    'entity.node.webform.test_form',
    // Webform Share module routes.
    'entity.webform.share_page',
    'entity.webform.share_page.javascript',
  ];
  if (in_array($route_name, $route_names)) {
    $variants = [];
    $element_keys = $webform
      ->getElementsVariant();
    foreach ($element_keys as $element_key) {
      $element = $webform
        ->getElement($element_key);
      if (!empty($element['#prepopulate']) && !empty($element['#randomize'])) {
        $variant_plugins = $webform
          ->getVariants(NULL, TRUE, $element_key);
        if ($variant_plugins
          ->count()) {
          $variants[$element_key] = array_values($variant_plugins
            ->getInstanceIds());
        }
        else {
          $attachments['#attached']['html_head'][] = [
            [
              '#type' => 'html_tag',
              '#tag' => 'script',
              '#value' => Markup::create("\n(function(){\n  try {\n    if (window.sessionStorage) {\n      var key = 'Drupal.webform.{$webform->id()}.variant.{$element_key}';\n      window.sessionStorage.removeItem(key);\n    }\n  }\n  catch(e) {}\n})();\n"),
              '#weight' => 1000,
            ],
            'webform_variant_' . $element_key . '_clear',
          ];
        }
      }
    }
    if ($variants) {

      // Using JavaScript for redirection allows pages to be cached
      // by URL with querystring parameters.
      $json_variants = Json::encode($variants);
      $attachments['#attached']['html_head'][] = [
        [
          '#type' => 'html_tag',
          '#tag' => 'script',
          '#value' => Markup::create("\n(function(){\n\n  var hasSessionStorage = (function () {\n    try {\n      sessionStorage.setItem('webform', 'webform');\n      sessionStorage.removeItem('webform');\n      return true;\n    }\n    catch (e) {\n      return false;\n    }\n  }());\n\n  function getSessionVariantID(variant_key) {\n    if (hasSessionStorage) {\n      var key = 'Drupal.webform.{$webform->id()}.variant.' + variant_key;\n      return window.sessionStorage.getItem(key);\n    }\n    return null;\n  }\n\n  function setSessionVariantID(variant_key, variant_id) {\n    if (hasSessionStorage) {\n      var key = 'Drupal.webform.{$webform->id()}.variant.' + variant_key;\n      window.sessionStorage.setItem(key, variant_id);\n    }\n  }\n\n  var variants = {$json_variants};\n  var search = location.search;\n  var element_key, variant_ids, variant_id;\n  for (element_key in variants) {\n    if (variants.hasOwnProperty(element_key)\n      && !search.match(new RegExp('[?&]' + element_key + '='))) {\n        variant_ids = variants[element_key];\n        variant_id = getSessionVariantID(element_key);\n        if (!variant_ids.includes(variant_id)) {\n          variant_id = variant_ids[Math.floor(Math.random() * variant_ids.length)];\n          setSessionVariantID(element_key, variant_id);\n        }\n        search += (search ? '&' : '?') + element_key + '=' + variant_id;\n    }\n  }\n  if (search !== location.search) {\n    location.replace(location.pathname + search);\n  }\n})();\n"),
          '#weight' => 1000,
        ],
        'webform_variant_randomize',
      ];
    }
  }
}