You are here

class ThemeSwitcherRuleForm in Theme Switcher Rules 8

Form handler for the ThemeSwitcherRule add and edit forms.

Hierarchy

Expanded class hierarchy of ThemeSwitcherRuleForm

File

src/Form/ThemeSwitcherRuleForm.php, line 19

Namespace

Drupal\theme_switcher\Form
View source
class ThemeSwitcherRuleForm extends EntityForm {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The logger factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

  /**
   * The ConditionManager for building the visibility UI.
   *
   * @var \Drupal\Core\Executable\ExecutableManagerInterface
   */
  protected $conditionPluginManager;

  /**
   * The context repository service.
   *
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
   */
  protected $contextRepository;

  /**
   * The language manager service.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Constructs an SwitchThemeRuleForm object.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\Core\Logger\LoggerChannelInterface $logger
   *   The logger.
   * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
   *   The theme handler.
   * @param \Drupal\Core\Executable\ExecutableManagerInterface $condition_plugin_manager
   *   The ConditionManager for building the visibility UI.
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
   *   The lazy context repository service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   */
  public function __construct(MessengerInterface $messenger, LoggerChannelInterface $logger, ThemeHandlerInterface $theme_handler, ExecutableManagerInterface $condition_plugin_manager, ContextRepositoryInterface $context_repository, LanguageManagerInterface $language_manager) {
    $this->messenger = $messenger;
    $this->logger = $logger;
    $this->themeHandler = $theme_handler;
    $this->conditionPluginManager = $condition_plugin_manager;
    $this->contextRepository = $context_repository;
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('messenger'), $container
      ->get('logger.factory')
      ->get('theme_switcher'), $container
      ->get('theme_handler'), $container
      ->get('plugin.manager.condition'), $container
      ->get('context.repository'), $container
      ->get('language_manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $available_contexts = $this->contextRepository
      ->getAvailableContexts();
    $form_state
      ->setTemporaryValue('gathered_contexts', $available_contexts);

    /** @var \Drupal\theme_switcher\Entity\ThemeSwitcherRule $entity */
    $entity = $this->entity;
    $form['#tree'] = TRUE;
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Theme Switcher Rule'),
      '#maxlength' => 255,
      '#default_value' => $entity
        ->label(),
      '#description' => $this
        ->t('The human-readable name is shown in the Theme Switcher list.'),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $entity
        ->id(),
      '#machine_name' => [
        'source' => [
          'label',
        ],
        'exists' => [
          $this,
          'exist',
        ],
      ],
      '#disabled' => !$entity
        ->isNew(),
    ];
    $form['status'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Theme Switcher Rule status'),
      '#options' => [
        1 => $this
          ->t('Active'),
        0 => $this
          ->t('Inactive'),
      ],
      '#default_value' => (int) $entity
        ->status(),
      '#description' => $this
        ->t('The Theme Switcher Rule will only work if the active option is set.'),
    ];
    $form['weight'] = [
      '#type' => 'weight',
      '#title' => $this
        ->t('Weight'),
      '#access' => FALSE,
      '#default_value' => $entity
        ->getWeight(),
      '#description' => $this
        ->t('The sort order for this record. Lower values display first.'),
    ];
    $form['theme'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Theme'),
      '#description' => $this
        ->t('The theme to apply in all pages that meet the conditions below.'),
      '#options' => $this
        ->getThemeOptions(),
      '#default_value' => $entity
        ->getTheme() ?? '',
      '#required' => TRUE,
    ];
    $form['admin_theme'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Admin Theme'),
      '#description' => $this
        ->t('The theme to apply in just the admin pages that meet the conditions below.'),
      '#options' => $this
        ->getThemeOptions(),
      '#default_value' => $entity
        ->getAdminTheme() ?? '',
    ];

    // Build the visibility UI form and follow this
    // https://www.drupal.org/node/2284687
    $form['visibility'] = [
      'visibility_tabs' => [
        '#type' => 'vertical_tabs',
        '#title' => $this
          ->t('Conditions'),
        '#parents' => [
          'visibility_tabs',
        ],
      ],
    ];
    $visibility = $entity
      ->getVisibility();
    $definitions = $this->conditionPluginManager
      ->getFilteredDefinitions('theme_switcher_ui', $form_state
      ->getTemporaryValue('gathered_contexts'), [
      'theme_switcher_rule' => $entity,
    ]);

    // Allows modules to alter the number the conditions.
    $this->moduleHandler
      ->alter('available_conditions', $definitions);
    foreach ($definitions as $condition_id => $definition) {

      /** @var \Drupal\Core\Condition\ConditionInterface $condition */
      $condition = $this->conditionPluginManager
        ->createInstance($condition_id, $visibility[$condition_id] ?? []);
      $form_state
        ->set([
        'conditions',
        $condition_id,
      ], $condition);
      $condition_form = $condition
        ->buildConfigurationForm([], $form_state);
      $form['visibility'][$condition_id] = [
        '#type' => 'details',
        '#title' => $condition
          ->getPluginDefinition()['label'],
        '#group' => 'visibility_tabs',
      ] + $condition_form;
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * The settings conditions context mappings is now the plugin responsibility
   * so we can avoid doing it here. From 8.2 the class ConditionPluginBase do
   * the job on submitConfigurationForm().
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    /** @var \Drupal\theme_switcher\Entity\ThemeSwitcherRule $entity */
    $entity = $this->entity;
    foreach ($form_state
      ->getValue('visibility') as $condition_id => $values) {

      // Allow the condition to submit the form.
      $condition = $form_state
        ->get([
        'conditions',
        $condition_id,
      ]);
      $subform = SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state);
      $condition
        ->submitConfigurationForm($form['visibility'][$condition_id], $subform);

      // Update the visibility conditions on the block.
      $entity
        ->getVisibilityConditions()
        ->addInstanceId($condition_id, $condition
        ->getConfiguration());
    }

    // Save the settings of the plugin.
    $status = $entity
      ->save();
    $message = $this
      ->t("The Theme Switcher Rule '%label' has been %op.", [
      '%label' => $entity
        ->label(),
      '%op' => $status == SAVED_NEW ? 'created' : 'updated',
    ]);
    $this->messenger
      ->addStatus($message);
    $this->logger
      ->notice($message);
    $form_state
      ->setRedirect('theme_switcher.admin');
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // Validate the weight.
    $form_state
      ->setValue('weight', (int) $form_state
      ->getValue('weight'));

    // Validate visibility condition settings.
    foreach ($form_state
      ->getValue('visibility') as $condition_id => $values) {

      // All condition plugins use 'negate' as a Boolean in their schema.
      // However, certain form elements may return it as 0/1. Cast here to
      // ensure the data is in the expected type.
      if (array_key_exists('negate', $values)) {
        $form_state
          ->setValue([
          'visibility',
          $condition_id,
          'negate',
        ], (bool) $values['negate']);
      }

      // Allow the condition to validate the form.
      $condition = $form_state
        ->get([
        'conditions',
        $condition_id,
      ]);
      $subform = SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state);
      $condition
        ->validateConfigurationForm($form['visibility'][$condition_id], $subform);
    }
  }

  /**
   * Return an array with all the themes.
   *
   * @return array
   *   An array with all the themes.
   */
  protected function getThemeOptions() {
    $output[''] = '- None -';
    foreach ($this->themeHandler
      ->listInfo() as $key => $value) {
      $output[$key] = $value
        ->getName();
    }
    return $output;
  }

  /**
   * Checks whether a theme_switcher_rule exists.
   *
   * @param string $id
   *   The theme_switcher_rule machine name.
   *
   * @return bool
   *   Whether the theme_switcher_rule exists.
   */
  public function exist($id) {
    $entity = $this->entityTypeManager
      ->getStorage('theme_switcher_rule')
      ->getQuery()
      ->condition('id', $id)
      ->execute();
    return (bool) $entity;
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 41
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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.
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 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.
ThemeSwitcherRuleForm::$conditionPluginManager protected property The ConditionManager for building the visibility UI.
ThemeSwitcherRuleForm::$contextRepository protected property The context repository service.
ThemeSwitcherRuleForm::$languageManager protected property The language manager service.
ThemeSwitcherRuleForm::$logger protected property The logger factory.
ThemeSwitcherRuleForm::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
ThemeSwitcherRuleForm::$themeHandler protected property The theme handler.
ThemeSwitcherRuleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ThemeSwitcherRuleForm::exist public function Checks whether a theme_switcher_rule exists.
ThemeSwitcherRuleForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
ThemeSwitcherRuleForm::getThemeOptions protected function Return an array with all the themes.
ThemeSwitcherRuleForm::submitForm public function The settings conditions context mappings is now the plugin responsibility so we can avoid doing it here. From 8.2 the class ConditionPluginBase do the job on submitConfigurationForm(). Overrides EntityForm::submitForm
ThemeSwitcherRuleForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ThemeSwitcherRuleForm::__construct public function Constructs an SwitchThemeRuleForm 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.