hovercss-1.0.3/hovercss_ui/src/Form/HoverCssForm.php

hovercss_ui/src/Form/HoverCssForm.php
<?php

namespace Drupal\hovercss_ui\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\hovercss_ui\HoverCssManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * HoverCSS add and edit hover form.
 *
 * @internal
 */
class HoverCssForm extends FormBase {

  /**
   * An array to store the variables.
   *
   * @var array
   */
  protected $variables = [];

  /**
   * Hover manager.
   *
   * @var \Drupal\hovercss_ui\HoverCssManagerInterface
   */
  protected $effectManager;

  /**
   * A config object for the hover settings.
   *
   * @var \Drupal\Core\Config\Config
   */
  protected $config;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * Constructs a new hover object.
   *
   * @param \Drupal\hovercss_ui\HoverCssManagerInterface $effect_manager
   *   The hover selector manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   A config factory for retrieving required config objects.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  public function __construct(HoverCssManagerInterface $effect_manager, ConfigFactoryInterface $config_factory, TimeInterface $time) {
    $this->effectManager = $effect_manager;
    $this->config = $config_factory->get('hovercss.settings');
    $this->time = $time;
  }

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

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

  /**
   * {@inheritdoc}
   *
   * @param array $form
   *   A nested array form elements comprising the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param int $hid
   *   (optional) Hover id to be passed on to
   *   \Drupal::formBuilder()->getForm() for use as the default value of the
   *   Hover ID form data.
   */
  public function buildForm(array $form, FormStateInterface $form_state, int $hid = 0) {
    // HoverCSS flags for specific form labels and suffix.
    $ms_unit_label = ' <span class="hovercss-unit-flag">ms</span>';

    $hover    = $this->effectManager->findById($hid) ?? [];
    $selector = $hover['selector'] ?? '';
    $label    = $hover['label'] ?? '';
    $comment  = $hover['comment'] ?? '';
    $status   = $hover['status'] ?? TRUE;
    $options  = [];

    // Handle the case when $hover is not an array or option is not set.
    if (is_array($hover) && isset($hover['options'])) {
      $options = unserialize($hover['options'], ['allowed_classes' => FALSE]) ?? '';
    }

    // Store hover id.
    $form['hover_id'] = [
      '#type'  => 'value',
      '#value' => $hid,
    ];

    // Load the HoverCSS configuration settings.
    $config = $this->config;

    // The default selector to use when detecting multiple hover elements.
    $form['selector'] = [
      '#title'         => $this->t('Selector'),
      '#type'          => 'textfield',
      '#required'      => TRUE,
      '#size'          => 64,
      '#maxlength'     => 256,
      '#default_value' => $selector,
      '#description'   => $this->t('Enter a valid element or a css selector.'),
    ];

    // The label of this selector.
    $form['label'] = [
      '#title'         => $this->t('Label'),
      '#type'          => 'textfield',
      '#required'      => FALSE,
      '#size'          => 32,
      '#maxlength'     => 32,
      '#default_value' => $label ?? '',
      '#description'   => $this->t('The label for this hover selector like <em>Login button</em>.'),
    ];

    // HoverCSS utilities,
    // Hover.css comes packed with a few utility classes to simplify its use.
    $form['options'] = [
      '#title' => $this->t('Hover options'),
      '#type'  => 'details',
      '#open'  => TRUE,
    ];

    // The animation to use.
    $form['options']['effect'] = [
      '#title'         => $this->t('Hover effect'),
      '#type'          => 'select',
      '#options'       => hovercss_effect_options(),
      '#default_value' => $options['effect'] ?? $config->get('options.effect'),
      '#description'   => $this->t('Select the effect name you want to use for CSS selector.'),
    ];

    // Hover.css provides the following delays.
    $form['options']['delay'] = [
      '#type'          => 'number',
      '#min'           => 0,
      '#title'         => $this->t('Delay'),
      '#default_value' => $options['delay'] ?? $config->get('options.delay'),
      '#field_suffix'  => $ms_unit_label,
      '#attributes'    => ['class' => ['hover-delay']],
    ];

    // Hover speed time and duration used as a prefix on CSS Variables.
    $form['options']['duration'] = [
      '#type'          => 'number',
      '#min'           => 0,
      '#title'         => $this->t('Duration'),
      '#default_value' => $options['duration'] ?? $config->get('options.duration'),
      '#field_suffix'  => $ms_unit_label,
      '#attributes'    => ['class' => ['hover-duration']],
    ];

    // Hover.css preview.
    // Hover.css preview.
    $form['preview'] = [
      '#type'   => 'details',
      '#title'  => $this->t('Hover preview'),
      '#open'   => TRUE,
    ];

    // Hover.css button effect.
    $form['preview']['hover_primary'] = [
      '#value'        => $this->t('Input button'),
      '#type'         => 'button',
      '#button_type'  => 'primary',
      '#attributes'   => ['class' => ['hover__sample']],
      '#prefix' => '<div class="hover__preview">',
    ];
    $form['preview']['hover_secondary'] = [
      '#type'   => 'markup',
      '#markup' => '<a class="hover__sample button" href="#">' . $this->t('Link button') . '</a>',
    ];
    $form['preview']['hover_custom'] = [
      '#type'   => 'markup',
      '#markup' => '<a class="hover__sample custom-button" href="#">' . $this->t('Custom button') . '</a>',
    ];
    $form['preview']['hover_icon'] = [
      '#type'   => 'markup',
      '#markup' => '<a class="hover__sample custom-button icon-button" href="#"><i class="fa fa-chevron-circle-right hvr-icon"></i>' . $this->t('Icon button') . '</a>',
      '#suffix' => '</div>',
    ];

    // The comment for describe hover settings and usage in website.
    $form['comment'] = [
      '#type'          => 'textarea',
      '#title'         => $this->t('Comment'),
      '#default_value' => $comment ?? '',
      '#description'   => $this->t('Describe this hover settings and usage in your website.'),
      '#rows'          => 2,
      '#weight'        => 96,
    ];

    // Enabled status for this hover.
    $form['status'] = [
      '#type'          => 'checkbox',
      '#title'         => $this->t('Enabled'),
      '#description'   => $this->t('Hover effect will appear on pages that have this selector.'),
      '#default_value' => $status ?? FALSE,
      '#weight'        => 99,
    ];

    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type'        => 'submit',
      '#value'       => $this->t('Save'),
      '#button_type' => 'primary',
      '#submit'      => [[$this, 'submitForm']],
    ];

    if ($hid != 0) {
      // Add a 'Remove' button for hover form.
      $form['actions']['delete'] = [
        '#type'       => 'link',
        '#title'      => $this->t('Delete'),
        '#url'        => Url::fromRoute('hovercss.delete', ['hid' => $hid]),
        '#attributes' => [
          'class' => [
            'action-link',
            'action-link--danger',
            'action-link--icon-trash',
          ],
        ],
      ];

      // Redirect to list for submit handler on edit form.
      $form['actions']['submit']['#submit'] = ['::submitForm', '::overview'];
    }
    else {
      // Add a 'Save and go to list' button for add form.
      $form['actions']['overview'] = [
        '#type'   => 'submit',
        '#value'  => $this->t('Save and go to list'),
        '#submit' => array_merge($form['actions']['submit']['#submit'], ['::overview']),
        '#weight' => 20,
      ];
    }

    return $form;
  }

  /**
   * Submit handler for removing hover.
   *
   * @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.
   */
  public function remove(array &$form, FormStateInterface $form_state) {
    $hover_id = $form_state->getValue('hover_id');
    $form_state->setRedirect('hovercss.delete', ['hid' => $hover_id]);
  }

  /**
   * Form submission handler for the 'overview' action.
   *
   * @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.
   */
  public function overview(array $form, FormStateInterface $form_state): void {
    $form_state->setRedirect('hovercss.admin');
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $hover_id = $form_state->getValue('hover_id');
    $is_new   = $hover_id == 0;
    $selector = trim($form_state->getValue('selector'));

    if ($is_new) {
      if ($this->effectManager->isHover($selector)) {
        $form_state->setErrorByName('selector', $this->t('This selector is already exists.'));
      }
    }
    else {
      if ($this->effectManager->findById($hover_id)) {
        $hover = $this->effectManager->findById($hover_id);

        if ($selector != $hover['selector'] && $this->effectManager->isHover($selector)) {
          $form_state->setErrorByName('selector', $this->t('This selector is already added.'));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    $hover_id = $values['hover_id'];
    $selector = trim($values['selector']);
    $label    = trim($values['label']);
    $comment  = trim($values['comment']);
    $status   = $values['status'];

    // Provide a label from selector if was empty.
    if (empty($label)) {
      $label = ucfirst(trim(preg_replace("/[^a-zA-Z0-9]+/", " ", $selector)));
    }

    // Set variables from main hover settings.
    $variables['effect']   = $values['effect'];
    $variables['delay']    = $values['delay'];
    $variables['duration'] = $values['duration'];

    // Get variables from other module.
    if (count($this->variables)) {
      $variables = array_merge($variables, $this->variables);
    }

    // Serialize options variables.
    $options = serialize($variables);

    // The Unix timestamp when the hover was most recently saved.
    $changed = $this->time->getCurrentTime();

    // Save hover.
    $this->effectManager->addHover($hover_id, $selector, $label, $comment, $changed, $status, $options);
    $this->messenger()
      ->addStatus($this->t('The selector %selector has been added.', ['%selector' => $selector]));

    // Flush caches so the updated config can be checked.
    drupal_flush_all_caches();
  }

}

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

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