altcolor-1.0.0-beta1/src/Form/ColorForm.php

src/Form/ColorForm.php
<?php

namespace Drupal\altcolor\Form;

use Drupal\altcolor\Plugin\AltColorPluginManagerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\TempStore\PrivateTempStore;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class for building a ColorForm.
 */
class ColorForm extends ConfigFormBase {

  /**
   * The temp store.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStore
   */
  private PrivateTempStore $tempStore;

  /**
   * An array of configuration names that should be editable.
   *
   * @var array
   */
  protected $editableConfig = [];

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Config\TypedConfigManagerInterface $typedConfigManager
   *   The typed configuration manager.
   * @param \Drupal\Core\TempStore\PrivateTempStoreFactory $temp_store_factory
   *   The temp store factory.
   * @param \Drupal\altcolor\Plugin\AltColorPluginManagerInterface $alternativeColorManager
   *   The alternative color manager.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $urlGenerator
   *   The URL generator.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    TypedConfigManagerInterface $typedConfigManager,
    PrivateTempStoreFactory $temp_store_factory,
    protected AltColorPluginManagerInterface $alternativeColorManager,
    protected UrlGeneratorInterface $urlGenerator,
    protected AccountProxyInterface $currentUser,
  ) {
    parent::__construct($config_factory, $typedConfigManager);
    $this->tempStore = $temp_store_factory->get('altcolor');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('tempstore.private'),
      $container->get('altcolor.manager'),
      $container->get('url_generator'),
      $container->get('current_user'),
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return $this->editableConfig;
  }

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

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $theme = '') {
    $config_key = $theme . '.settings';
    $this->editableConfig = [$config_key];

    // Set the theme to be previewed in the temp store.
    $this->tempStore->set($this->currentUser->id() . ':preview_theme', $theme);

    // Define $colors and $schemes.
    $colors = $this->alternativeColorManager->getColorDefinitionsByTheme($theme)->getColors();
    $schemes = $this->alternativeColorManager->getColorDefinitionsByTheme($theme)->getSchemes();

    $form['altcolor'] = [
      '#type' => 'details',
      '#title' => t('Color scheme'),
      '#open' => TRUE,
      '#attributes' => [
        'id' => 'altcolor_form',
      ],
      '#attached' => [
        'library' => [
          'altcolor/altcolor.admin',
        ],
        'drupalSettings' => [
          'altcolor' => [
            'colorSchemes' => $schemes,
          ],
        ],
      ],
    ];

    $form['altcolor']['colors'] = [
      '#type' => 'container',
    ];

    $form['altcolor']['colors']['scheme'] = [
      '#type' => 'select',
      '#title' => $this->t('Color scheme'),
      '#options' => array_combine(array_keys($schemes), array_column($schemes, 'label')),
      '#empty_option' => $this->t('Custom'),
      '#empty_value' => NULL,
    ];

    $form['altcolor']['colors']['colors'] = [
      '#type' => 'container',
      '#title' => $this->t('Colors'),
      '#tree' => TRUE,
      '#parents' => ['altcolor', 'colors'],
    ];
    foreach ($colors as $variable => $label) {
      // If the color is not yet configured, try to fetch it from the first
      // color scheme.
      $fallback_color = array_values($schemes)[0]['colors'][$variable] ?? NULL;
      $form['altcolor']['colors']['colors'][$variable] = [
        '#type' => 'color',
        // @todo When we make plugin instances from the definitions, mark the
        //   labels as translatable and use the translated values.
        '#title' => $label['label'],
        '#default_value' => $this->altcolorPaletteColorValue($variable, $fallback_color),
        '#attributes' => [
          'data-altcolor-name' => $variable,
        ],
      ];
    }

    $form['altcolor']['preview'] = [
      '#type' => 'container',
    ];

    $form['altcolor']['preview']['preview'] = [
      '#type' => 'html_tag',
      '#tag' => 'iframe',
      '#attributes' => [
        // The path contains the altcolor_preview_theme query parameter,
        // allowing this module's theme negotiator to force a theme for the
        // preview within the iFrame. This renders the front page in the same
        // theme this settings page is about.
        'src' => $this->urlGenerator->generateFromRoute(
          '<front>',
          [],
          ['absolute' => TRUE, 'query' => ['altcolor_preview' => 1]]
        ),
        'allow' => 'fullscreen',
        'name' => 'altcolor-preview-frame',
        'style' => 'width:100%; height: 100%; min-height: 650px; zoom: 0.8;',
      ],
      '#prefix' => '<strong>This is the real website. Any changes made here will have an immediate effect.</strong>',
      '#attached' => [
        'library' => [
          'altcolor/altcolor.preview',
        ],
      ],
    ];

    return $form;
  }

  /**
   * Determines the value for a color field.
   *
   * @return string
   *   The HEX color value to set for the field.
   */
  public function altcolorPaletteColorValue($key, $fallback_value) {
    $color_settings = $this->config($this->editableConfig[0])->get('third_party_settings.altcolor.colors');
    if (!empty($color_settings[$key])) {
      return $color_settings[$key];
    }
    return $fallback_value;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc