You are here

class WebformAdminConfigLibrariesForm in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Form/AdminConfig/WebformAdminConfigLibrariesForm.php \Drupal\webform\Form\AdminConfig\WebformAdminConfigLibrariesForm

Configure webform admin settings for libraries.

Hierarchy

Expanded class hierarchy of WebformAdminConfigLibrariesForm

1 string reference to 'WebformAdminConfigLibrariesForm'
webform.routing.yml in ./webform.routing.yml
webform.routing.yml

File

src/Form/AdminConfig/WebformAdminConfigLibrariesForm.php, line 14

Namespace

Drupal\webform\Form\AdminConfig
View source
class WebformAdminConfigLibrariesForm extends WebformAdminConfigBaseForm {

  /**
   * The webform libraries manager.
   *
   * @var \Drupal\webform\WebformLibrariesManagerInterface
   */
  protected $librariesManager;

  /**
   * Array of webform library machine names.
   *
   * @var array
   */
  protected $libraries;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'webform_admin_config_libraries_form';
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->librariesManager = $container
      ->get('webform.libraries_manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('webform.settings');

    // Assets.
    $form['assets'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('CSS / JavaScript'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ];
    $form['assets']['description'] = [
      '#type' => 'webform_message',
      '#message_message' => $this
        ->t('The below CSS and JavasScript will be loaded on all webform pages.'),
      '#message_type' => 'info',
    ];
    $form['assets']['css'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'css',
      '#title' => $this
        ->t('CSS'),
      '#description' => $this
        ->t('Enter custom CSS to be attached to the all webforms.') . '<br/>' . $this
        ->t("To customize only webform specific elements, you should use the '.webform-submission-form' selector"),
      '#default_value' => $config
        ->get('assets.css'),
    ];
    $form['assets']['javascript'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'javascript',
      '#title' => $this
        ->t('JavaScript'),
      '#description' => $this
        ->t('Enter custom JavaScript to be attached to all webforms.'),
      '#default_value' => $config
        ->get('assets.javascript'),
    ];

    // Libraries optional.
    $form['libraries_optional'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('External optional libraries'),
      '#description' => $this
        ->t('Uncheck the below optional external libraries that you do not want to be used by any webforms.') . '</br>' . '<em>' . $this
        ->t('Please note, you can also exclude element types that are dependent on specific libraries.') . '</em>',
      '#open' => TRUE,
    ];
    $libraries_header = [
      'title' => [
        'data' => $this
          ->t('Title'),
      ],
      'version' => [
        'data' => $this
          ->t('Version'),
      ],
      'description' => [
        'data' => $this
          ->t('Description/Notes'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      'elements' => [
        'data' => $this
          ->t('Required elements'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      'provider' => [
        'data' => $this
          ->t('Provider'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      'resources' => [
        'data' => $this
          ->t('Resources'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
    ];
    $this->libraries = [];
    $libraries_optional_options = [];
    $libraries_required_option = [];
    $libraries = $this->librariesManager
      ->getLibraries();
    foreach ($libraries as $library_name => $library) {
      $operations = [];
      $operations['homepage'] = [
        'title' => $this
          ->t('Homepage'),
        'url' => $library['homepage_url'],
      ];
      if (isset($library['download_url'])) {
        $operations['download'] = [
          'title' => $this
            ->t('Download'),
          'url' => $library['download_url'],
        ];
      }
      if (isset($library['issues_url'])) {
        $issues_url = $library['issues_url'];
      }
      elseif (isset($library['download_url']) && preg_match('#https://github.com/[^/]+/[^/]+#', $library['download_url']
        ->toString(), $match)) {
        $issues_url = Url::fromUri($match[0] . '/issues');
      }
      else {
        $issues_url = NULL;
      }
      if ($issues_url) {
        $operations['issues'] = [
          'title' => $this
            ->t('Open Issues'),
          'url' => $issues_url,
        ];
        $accessibility_url = clone $issues_url;
        $operations['accessibility'] = [
          'title' => $this
            ->t('Accessibility Issues'),
          'url' => $accessibility_url
            ->setOption('query', [
            'q' => 'is:issue is:open accessibility ',
          ]),
        ];
      }
      $library_option = [
        'title' => $library['title'],
        'version' => $library['version'],
        'description' => [
          'data' => [
            'content' => [
              '#markup' => $library['description'],
              '#suffix' => '<br />',
            ],
            'notes' => [
              '#markup' => '(' . $library['notes'] . ')',
              '#prefix' => '<em>',
              '#suffix' => '</em><br />',
            ],
            'status' => !empty($library['deprecated']) ? [
              '#markup' => $library['deprecated'],
              '#prefix' => '<div class="color-warning"><strong>',
              '#suffix' => '</strong></div>',
            ] : [],
          ],
        ],
        'elements' => [
          'data' => [
            '#markup' => isset($library['elements']) ? implode('<br/>', $library['elements']) : '',
          ],
        ],
        'provider' => $library['provider'],
        'resources' => [
          'data' => [
            '#type' => 'operations',
            '#links' => $operations,
            '#prefix' => '<div class="webform-dropbutton">',
            '#suffix' => '</div>',
          ],
        ],
      ];

      // Only optional libraries can be excluded.
      if (empty($library['optional'])) {
        $libraries_required_options[$library_name] = $library_option;
      }
      else {
        $this->libraries[$library_name] = $library_name;
        $libraries_optional_options[$library_name] = $library_option;
      }
    }
    $form['libraries_optional']['excluded_libraries'] = [
      '#type' => 'tableselect',
      '#title' => $this
        ->t('Libraries'),
      '#header' => $libraries_header,
      '#js_select' => FALSE,
      '#options' => $libraries_optional_options,
      '#default_value' => array_diff($this->libraries, array_combine($config
        ->get('libraries.excluded_libraries'), $config
        ->get('libraries.excluded_libraries'))),
    ];
    TableSelect::setProcessTableSelectCallback($form['libraries_optional']['excluded_libraries']);

    // Display warning message about select2, choices and chosen.
    $t_args = [
      ':select2_href' => $libraries['jquery.select2']['homepage_url']
        ->toString(),
      ':choices_href' => $libraries['choices']['homepage_url']
        ->toString(),
      ':chosen_href' => $libraries['jquery.chosen']['homepage_url']
        ->toString(),
    ];
    $form['libraries_optional']['select_message'] = [
      '#type' => 'webform_message',
      '#message_type' => 'warning',
      '#message_message' => $this
        ->t('<a href=":select2_href">Select2</a>, <a href=":choices_href">Choices</a>, and <a href=":chosen_href">Chosen</a> provide very similar functionality, most websites should only have one of these libraries enabled.', $t_args),
      '#message_close' => TRUE,
      '#message_storage' => WebformMessage::STORAGE_SESSION,
    ];

    // Libraries required.
    if ($libraries_required_option) {
      $form['libraries_required'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('External required libraries'),
        '#description' => $this
          ->t('The below external libraries are required by specified webform elements or modules.'),
        '#open' => TRUE,
      ];
      $form['libraries_required']['required_libraries'] = [
        '#type' => 'table',
        '#header' => $libraries_header,
        '#rows' => $libraries_required_options,
      ];
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Convert list of included types to excluded types.
    $excluded_libraries = array_diff($this->libraries, array_filter($form_state
      ->getValue('excluded_libraries')));
    ksort($excluded_libraries);

    // Note: Must store a simple array of libraries because library names
    // may contain periods, which is not supported by Drupal's
    // config management.
    $excluded_libraries = array_keys($excluded_libraries);

    // Update config and submit form.
    $config = $this
      ->config('webform.settings');
    $config
      ->set('assets', $form_state
      ->getValue('assets'));
    $config
      ->set('libraries.excluded_libraries', $excluded_libraries);
    parent::submitForm($form, $form_state);

    // Reset libraries cached.
    // @see webform_library_info_build()
    \Drupal::service('library.discovery')
      ->clearCachedDefinitions();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 16
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 72
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
WebformAdminConfigBaseForm::buildBulkOperations protected function Build bulk operation settings for webforms and submissions.
WebformAdminConfigBaseForm::buildExcludedPlugins protected function Build excluded plugins element.
WebformAdminConfigBaseForm::convertIncludedToExcludedPluginIds protected function Convert included ids returned from table select element to excluded ids.
WebformAdminConfigBaseForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
WebformAdminConfigBaseForm::getPluginDefinitions protected function Get plugin definitions.
WebformAdminConfigBaseForm::validateBulkFormActions public static function Form API callback. Validate bulk form actions.
WebformAdminConfigLibrariesForm::$libraries protected property Array of webform library machine names.
WebformAdminConfigLibrariesForm::$librariesManager protected property The webform libraries manager.
WebformAdminConfigLibrariesForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
WebformAdminConfigLibrariesForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
WebformAdminConfigLibrariesForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformAdminConfigLibrariesForm::submitForm public function Form submission handler. Overrides WebformAdminConfigBaseForm::submitForm