You are here

class SwitchForm in Domain Access 8

Class SwitchForm.

Hierarchy

Expanded class hierarchy of SwitchForm

File

domain_config_ui/src/Form/SwitchForm.php, line 21

Namespace

Drupal\domain_config_ui\Form
View source
class SwitchForm extends FormBase {

  /**
   * The domain entity access control handler.
   *
   * @var \Drupal\domain\DomainAccessControlHandler
   */
  protected $accessHandler;

  /**
   * Constructs a new DevelGenerateForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\domain_config_ui\DomainConfigUIManager $domain_config_ui_manager
   *   The domain config UI manager.
   * @param \Drupal\domain\DomainElementManagerInterface $domain_element_manager
   *   The domain field element manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, DomainConfigUIManager $domain_config_ui_manager, DomainElementManagerInterface $domain_element_manager) {
    $this->domainConfigUiManager = $domain_config_ui_manager;
    $this->languageManager = $language_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->domainStorage = $this->entityTypeManager
      ->getStorage('domain');
    $this->domainElementManager = $domain_element_manager;

    // Not loaded directly since it is not an interface.
    $this->accessHandler = $this->entityTypeManager
      ->getAccessControlHandler('domain');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('language_manager'), $container
      ->get('domain_config_ui.manager'), $container
      ->get('domain.element_manager'));
  }

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

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

    // Only allow access to domain administrators.
    $form['#access'] = $this
      ->canUseDomainConfig();
    $form = $this
      ->addSwitchFields($form, $form_state);
    return $form;
  }

  /**
   * Determines if a user may access the domain-sensitive form.
   */
  public function canUseDomainConfig() {
    if ($this
      ->currentUser()
      ->hasPermission('administer domains')) {
      $user_domains = 'all';
    }
    else {
      $account = $this
        ->currentUser();
      $user = $this->entityTypeManager
        ->getStorage('user')
        ->load($account
        ->id());
      $user_domains = $this->domainElementManager
        ->getFieldValues($user, DomainInterface::DOMAIN_ADMIN_FIELD);
    }
    $permission = $this
      ->currentUser()
      ->hasPermission('use domain config ui') || $this
      ->currentUser()
      ->hasPermission('administer domain config ui');
    return !empty($user_domains) && $permission;
  }

  /**
   * Helper to add switch fields to form.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state array.
   */
  public function addSwitchFields(array $form, FormStateInterface $form_state) {

    // Create fieldset to group domain fields.
    $form['domain_config_ui'] = [
      '#type' => 'fieldset',
      '#title' => 'Domain Configuration',
      '#weight' => -10,
    ];

    // Add domain switch select field.
    if ($selected_domain_id = $this->domainConfigUiManager
      ->getSelectedDomainId()) {
      $selected_domain = $this->domainStorage
        ->load($selected_domain_id);
    }

    // Get the form options.
    $form['domain_config_ui']['domain'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Domain'),
      '#options' => $this
        ->getDomainOptions(),
      '#default_value' => !empty($selected_domain) ? $selected_domain
        ->id() : '',
      '#ajax' => [
        'callback' => '::switchCallback',
      ],
    ];

    // Add language select field. Domain Config does not rely on core's Config
    // Translation module, so we set our own permission.
    $languages = $this->languageManager
      ->getLanguages();
    if (count($languages) > 1 && $this
      ->currentUser()
      ->hasPermission('translate domain configuration')) {
      $language_options = [
        '' => $this
          ->t('Default'),
      ];
      foreach ($languages as $id => $language) {
        if (!$language
          ->isLocked()) {
          $language_options[$id] = $language
            ->getName();
        }
      }
      $form['domain_config_ui']['language'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Language'),
        '#options' => $language_options,
        '#default_value' => $this->domainConfigUiManager
          ->getSelectedLanguageId(),
        '#ajax' => [
          'callback' => '::switchCallback',
        ],
      ];
      $form['domain_config_ui']['help'] = [
        '#markup' => $this
          ->t('Changing the domain or language will load its active configuration.'),
      ];
    }
    else {
      $form['domain_config_ui']['help'] = [
        '#markup' => $this
          ->t('Changing the domain will load its active configuration.'),
      ];
    }

    // @TODO: Add cache contexts to form?
    return $form;
  }

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

    // Form does not require submit handler.
  }

  /**
   * Callback to remember save mode and reload page.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state array.
   */
  public static function switchCallback(array &$form, FormStateInterface $form_state) {

    // Extract requesting page URI from ajax URI.
    // Copied from Drupal\Core\Form\FormBuilder::buildFormAction().
    $request = \Drupal::service('request_stack')
      ->getMasterRequest();
    $request_uri = $request
      ->getRequestUri();

    // Prevent cross site requests via the Form API by using an absolute URL
    // when the request uri starts with multiple slashes.
    if (strpos($request_uri, '//') === 0) {
      $request_uri = $request
        ->getUri();
    }
    $parsed = UrlHelper::parse($request_uri);
    unset($parsed['query']['ajax_form'], $parsed['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
    if (\Drupal::config('domain_config_ui.settings')
      ->get('remember_domain')) {

      // Save domain and language on session.
      $_SESSION['domain_config_ui_domain'] = $form_state
        ->getValue('domain');
      $_SESSION['domain_config_ui_language'] = $form_state
        ->getValue('language');
    }
    else {

      // Pass domain and language as request query parameters.
      $parsed['query']['domain_config_ui_domain'] = $form_state
        ->getValue('domain');
      $parsed['query']['domain_config_ui_language'] = $form_state
        ->getValue('language');
    }
    $request_uri = $parsed['path'] . ($parsed['query'] ? '?' . UrlHelper::buildQuery($parsed['query']) : '');

    // Reload the page to get new form values.
    $response = new AjaxResponse();
    $response
      ->addCommand(new RedirectCommand($request_uri));
    return $response;
  }

  /**
   * Gets the available domain list for the form user.
   *
   * @return array
   *   An array of select options.
   */
  public function getDomainOptions() {
    $domains = $this->domainStorage
      ->loadMultipleSorted();
    $options = [];
    foreach ($domains as $domain) {

      // If the user cannot view the domain, then don't show in the list.
      // View here is sufficient, because it means the user is assigned to the
      // domain. We have already checked for the ability to use this form.
      $access = $this->accessHandler
        ->checkAccess($domain, 'view');
      if ($access
        ->isAllowed()) {
        $options[$domain
          ->id()] = $domain
          ->label();
      }
    }

    // The user must have permission to set the default value.
    if ($this
      ->currentUser()
      ->hasPermission('set default domain configuration')) {
      $options = array_merge([
        '' => $this
          ->t('All Domains'),
      ], $options);
    }
    return $options;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
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. Overrides UrlGeneratorTrait::redirect
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 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
SwitchForm::$accessHandler protected property The domain entity access control handler.
SwitchForm::addSwitchFields public function Helper to add switch fields to form.
SwitchForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
SwitchForm::canUseDomainConfig public function Determines if a user may access the domain-sensitive form.
SwitchForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SwitchForm::getDomainOptions public function Gets the available domain list for the form user.
SwitchForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SwitchForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
SwitchForm::switchCallback public static function Callback to remember save mode and reload page.
SwitchForm::__construct public function Constructs a new DevelGenerateForm object.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.