You are here

class StyleswitcherStyleForm in Style Switcher 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Form/StyleswitcherStyleForm.php \Drupal\styleswitcher\Form\StyleswitcherStyleForm

Provides a form to add/edit a style.

Hierarchy

Expanded class hierarchy of StyleswitcherStyleForm

1 string reference to 'StyleswitcherStyleForm'
styleswitcher.routing.yml in ./styleswitcher.routing.yml
styleswitcher.routing.yml

File

src/Form/StyleswitcherStyleForm.php, line 15

Namespace

Drupal\styleswitcher\Form
View source
class StyleswitcherStyleForm extends FormBase {

  /**
   * The theme manager.
   *
   * @var \Drupal\Core\Theme\ThemeManagerInterface
   */
  protected $themeManager;

  /**
   * Constructs the StyleswitcherStyleForm.
   *
   * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
   *   The theme manager.
   */
  public function __construct(ThemeManagerInterface $theme_manager) {
    $this->themeManager = $theme_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('theme.manager'));
  }

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

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array|null $style
   *   (optional) Style to edit. The structure of an array is the same as
   *   returned from styleswitcher_style_load().
   *
   * @return array
   *   The form structure.
   *
   * @see styleswitcher_style_load()
   */
  public function buildForm(array $form, FormStateInterface $form_state, $style = NULL) {
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Title'),
      '#description' => $this
        ->t('Human-readable name for this style.'),
      '#default_value' => $style ? $style['label'] : '',
      '#required' => TRUE,
    ];
    if ($style) {
      list(, $name_value) = explode('/', $style['name']);
    }
    $form['name'] = [
      '#type' => 'machine_name',
      '#description' => $this
        ->t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
      '#default_value' => $style ? $name_value : '',
      '#field_prefix' => 'custom/',
      '#machine_name' => [
        'source' => [
          'label',
        ],
        'exists' => [
          $this,
          'exists',
        ],
      ],
    ];
    if ($style) {

      // Show the warning about renaming styles.
      $form['name']['#description'] .= '<br />' . $this
        ->t('<strong>WARNING:</strong> if you change style machine name, users who have chosen this style will see the default one instead until they switch again.');
    }
    $form['old_name'] = [
      '#type' => 'value',
      '#value' => $style ? $style['name'] : '',
    ];
    $form['path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Path'),
      '#description' => $this
        ->t('The path to the stylesheet file relative to the site root or an external CSS file.'),
      '#default_value' => $style ? $style['path'] : '',
      '#required' => TRUE,
      '#access' => !$style || isset($style['path']),
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    ];
    if ($style) {
      $form['actions']['delete'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Delete'),
        '#url' => Url::fromRoute('styleswitcher.style_delete', [
          'style' => $name_value,
        ]),
        '#attributes' => [
          'class' => [
            'button',
            'button--danger',
          ],
        ],
        // Do not allow to delete the blank style.
        '#access' => isset($style['path']),
      ];
    }
    return $form;
  }

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

    // Trim text values now, so submission handlers get them fully validated.
    // No need to trim name, because it's validated by a machine-name pattern.
    $form_state
      ->setValueForElement($form['label'], trim($form_state
      ->getValue('label')));
    $path = $form_state
      ->getValue('path');
    if ($path === '') {

      // Set the path back to NULL.
      $form_state
        ->setValueForElement($form['path'], NULL);
    }
    else {
      $path = trim($path);
      $form_state
        ->setValueForElement($form['path'], $path);
      if (!is_file($path) && !UrlHelper::isExternal($path)) {
        $form_state
          ->setErrorByName('path', $this
          ->t('Stylesheet file %path does not exist.', [
          '%path' => $path,
        ]));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $old_name = $form_state
      ->getValue('old_name');
    $styles = styleswitcher_custom_styles();
    $style = [
      'label' => $form_state
        ->getValue('label'),
      'name' => 'custom/' . $form_state
        ->getValue('name'),
      'path' => $form_state
        ->getValue('path'),
    ];
    if ($old_name !== '') {
      unset($styles[$old_name]);

      // Update style keys in settings variable.
      if ($style['name'] != $old_name) {
        $config = $this
          ->configFactory()
          ->getEditable('styleswitcher.styles_settings');
        $settings = $config
          ->get('settings') ?? [];
        foreach (array_keys($settings) as $theme) {
          if (isset($settings[$theme][$old_name])) {
            $settings[$theme][$style['name']] = $settings[$theme][$old_name];
            unset($settings[$theme][$old_name]);
          }
        }
        $config
          ->set('settings', $settings)
          ->save();
      }
    }
    $styles[$style['name']] = $style;
    $this
      ->configFactory()
      ->getEditable('styleswitcher.custom_styles')
      ->set('styles', $styles)
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('The style %title has been saved.', [
      '%title' => $style['label'],
    ]));
    $form_state
      ->setRedirect('styleswitcher.admin');
  }

  /**
   * The _title_callback for the style edit form.
   *
   * @param array $style
   *   Style array as returned from styleswitcher_style_load().
   *
   * @return string
   *   Label of the style.
   *
   * @see styleswitcher_style_load()
   */
  public function title(array $style) {
    return $style['label'];
  }

  /**
   * Checks whether a submitted machine name value already exists.
   *
   * @param string $input
   *   User-submitted value.
   *
   * @return array|null
   *   Style array on success or NULL otherwise. Style is an associative array
   *   as returned from styleswitcher_style_load().
   *
   * @see styleswitcher_style_load()
   */
  public function exists($input) {

    // It does not matter what theme to set in this load call, because all
    // custom styles exist in all themes. Let's set one from the current page
    // just to decrease calculations.
    $active_theme_name = $this->themeManager
      ->getActiveTheme()
      ->getName();
    return styleswitcher_style_load($input, $active_theme_name, 'custom');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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.
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.
StyleswitcherStyleForm::$themeManager protected property The theme manager.
StyleswitcherStyleForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
StyleswitcherStyleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
StyleswitcherStyleForm::exists public function Checks whether a submitted machine name value already exists.
StyleswitcherStyleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StyleswitcherStyleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
StyleswitcherStyleForm::title public function The _title_callback for the style edit form.
StyleswitcherStyleForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
StyleswitcherStyleForm::__construct public function Constructs the StyleswitcherStyleForm.