You are here

class AdminSettingsForm in Role Based Theme Switcher 8

Same name and namespace in other branches
  1. 9.1.x src/Form/AdminSettingsForm.php \Drupal\role_based_theme_switcher\Form\AdminSettingsForm

Configure Role Based settings for this site.

@category Role_Based_Theme_Switcher

@package Role_Based_Theme_Switcher

@link https://www.drupal.org/sandbox/pen/2760771 description

Hierarchy

Expanded class hierarchy of AdminSettingsForm

1 string reference to 'AdminSettingsForm'
role_based_theme_switcher.routing.yml in ./role_based_theme_switcher.routing.yml
role_based_theme_switcher.routing.yml

File

src/Form/AdminSettingsForm.php, line 21

Namespace

Drupal\role_based_theme_switcher\Form
View source
class AdminSettingsForm extends ConfigFormBase {

  /**
   * Protected themeGlobal variable.
   *
   * @var themeGlobal
   */
  protected $themeGlobal;

  /**
   * Protected configFactory variable.
   *
   * @var configFactory
   */
  protected $configFactory;

  /**
   * {@inheritdoc}
   */
  public function __construct(ThemeHandler $themeGlobal, ConfigFactoryInterface $config_factory) {
    $this->themeGlobal = $themeGlobal;
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('theme_handler'), $container
      ->get('config.factory'));
  }

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

  /**
   * {@inheritdoc}
   *
   * Implements admin settings form.
   *
   * @param array $form
   *   From render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Current state of form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Load Themes List.
    $themes = $this->themeGlobal
      ->listInfo();

    // Prepare array.
    $themeNames = [
      '' => '--Select--',
    ];
    foreach ($themes as $key => $value) {
      $themeNames[$key] = $key;
    }

    // Load Roles.
    $roles = Role::loadMultiple();
    $roleThemes = $this->configFactory
      ->get('role_based_theme_switcher.RoleBasedThemeSwitchConfig')
      ->get('roletheme');
    $form['role_theme'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Label'),
        $this
          ->t('Themes List'),
        $this
          ->t('Weight'),
      ],
      '#empty' => $this
        ->t('There are no items yet. Add an item.', []),
      // TableDrag: Each array value is a list of callback arguments for
      // drupal_add_tabledrag().The #id of the table is automatically prepended;
      // if there is none, an HTML ID is auto-generated.
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'role_theme-order-weight',
        ],
      ],
    ];

    // Check if anything is assigned.
    // If any role is aasigned any theme.
    // Else Load list of themes on with all roles.
    if (!empty($roleThemes)) {

      // Check if any new role is added.
      // If yes then merge new roles also.
      if (count($roleThemes) == count($roles)) {
        $roles = $roleThemes;
      }
      elseif (count($roleThemes) != count($roles)) {
        foreach ($roles as $rem_key => $rem_val) {
          if (!array_key_exists($rem_key, $roleThemes)) {
            $merge[$rem_key] = [
              'id' => '',
              'weight' => 10,
            ];
            $roleThemes = array_merge($roleThemes, $merge);
          }
        }
        $roles = $roleThemes;
      }
    }
    else {
      $roleThemes = [];
      $i = 0;
      foreach ($roles as $roles_key => $roles_val) {
        if ($roles_key == 'administrator') {
          $roleThemes[$roles_key]['weight'] = $i;
          $roleThemes[$roles_key]['id'] = 'seven';
          $i++;
        }
        else {
          $roleThemes[$roles_key]['weight'] = $i;
          $roleThemes[$roles_key]['id'] = 'bartik';
          $i++;
        }
      }
      $roles = $roleThemes;
    }

    // Build the table rows and columns.
    foreach ($roles as $id => $entity) {

      // TableDrag: Mark the table row as draggable.
      $form['role_theme'][$id]['#attributes']['class'][] = 'draggable';

      // TableDrag: Sort the table row according to its existing/configured
      // weight.
      // $form['role_theme'][$id]['#weight'] = (int) $roleThemes[$id]['weight'];
      // Some table columns containing raw markup.
      $form['role_theme'][$id]['label'] = [
        '#plain_text' => $this
          ->t('@id User', [
          '@id' => ucfirst($id),
        ]),
      ];
      $form['role_theme'][$id]['id'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Select Theme'),
        '#options' => $themeNames,
        '#default_value' => (string) $roleThemes[$id]['id'],
      ];

      // TableDrag: Weight column element.
      $form['role_theme'][$id]['weight'] = [
        '#type' => 'weight',
        '#title_display' => 'invisible',
        '#default_value' => (int) $roleThemes[$id]['weight'],
        // Classify the weight element for #tabledrag.
        '#attributes' => [
          'class' => [
            'role_theme-order-weight',
          ],
        ],
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save changes'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $rollTheme = $form_state
      ->getValue('role_theme');
    $role_arr = [];
    foreach ($rollTheme as $key => $value) {
      if (in_array((int) $value['weight'], $role_arr)) {
        $form_state
          ->setErrorByName('role_theme', $this
          ->t("There are errors in the form"));
      }
      $role_arr[$key] = (int) $value['weight'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $rollTheme = $form_state
      ->getValue('role_theme');
    $role_arr = [];
    foreach ($rollTheme as $key => $value) {
      $role_arr[(int) $value['weight']] = [
        'theme' => $value['id'],
        'role' => $key,
      ];
      $roles[] = $key;
    }
    ksort($role_arr);
    foreach ($role_arr as $new_key => $new_value) {
      if (in_array($new_value['role'], $roles)) {
        $roll_array[$new_value['role']] = [
          'id' => $new_value['theme'],
          'weight' => $new_key,
        ];
      }
    }
    $roleThemes = $this
      ->config('role_based_theme_switcher.RoleBasedThemeSwitchConfig');
    $roleThemes
      ->set('roletheme', $roll_array);
    $roleThemes
      ->save();
    $this
      ->messenger()
      ->addMessage($this
      ->t("Role theme configuration saved succefully"));

    // Clearing cache for anonymous users.
    drupal_flush_all_caches();
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'role_based_theme_switcher.RoleBasedThemeSwitchConfig',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AdminSettingsForm::$configFactory protected property Protected configFactory variable. Overrides FormBase::$configFactory
AdminSettingsForm::$themeGlobal protected property Protected themeGlobal variable.
AdminSettingsForm::buildForm public function Implements admin settings form. Overrides ConfigFormBase::buildForm
AdminSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
AdminSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AdminSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AdminSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AdminSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
AdminSettingsForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::$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. 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 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.
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.