improvements-2.x-dev/modules/improvements_form/src/Element/RangeSlider.php

modules/improvements_form/src/Element/RangeSlider.php
<?php

namespace Drupal\improvements_form\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;

/**
 * @FormElement("range_slider")
 */
class RangeSlider extends FormElement {

  /**
   * {@inheritDoc}
   */
  public function getInfo(): array {
    $class = get_class($this);

    return [
      '#input' => TRUE,
      '#process' => [
        [$class, 'processElement'],
      ],
      '#theme_wrappers' => ['form_element'],
      '#min' => NULL,
      '#max' => NULL,
      '#step' => NULL,
      '#validate_numbers' => TRUE,
    ];
  }

  /**
   * Element process callback.
   */
  public static function processElement(array &$element, FormStateInterface $form_state, array &$complete_form): array {
    $element['#tree'] = TRUE;

    $step = $element['#step'] ?? NULL;

    if ($step > 1) {
      if (isset($element['#min'])) {
        $element['#min'] = floor($element['#min'] / $step) * $step;
      }
      if (isset($element['#max'])) {
        $element['#max'] = ceil($element['#max'] / $step) * $step;
      }
    }

    $element['min'] = [
      '#type' => 'number',
      '#title' => t('From', [], ['context' => 'number']),
      '#default_value' => $element['#default_value']['min'] ?? '',
      '#min' => $element['#min'] ?? NULL,
      '#max' => $element['#max'] ?? NULL,
      '#step' => $step,
      '#wrapper_attributes' => [
        'class' => ['form-range-slider__min-item'],
      ],
      '#attributes' => [
        'class' => ['form-range-slider__min'],
      ],
    ];

    $element['max'] = [
      '#type' => 'number',
      '#title' => t('To', [], ['context' => 'number']),
      '#default_value' => $element['#default_value']['max'] ?? '',
      '#min' => $element['#min'] ?? NULL,
      '#max' => $element['#max'] ?? NULL,
      '#step' => $step,
      '#wrapper_attributes' => [
        'class' => ['form-range-slider__max-item'],
      ],
      '#attributes' => [
        'class' => ['form-range-slider__max'],
      ],
    ];

    if (!$element['#validate_numbers']) {
      $element['min']['#element_validate'] = [];
      $element['max']['#element_validate'] = [];
    }

    $element['slider'] = [
      '#markup' => '<div class="form-range-slider__slider"></div>',
    ];

    $element['#wrapper_attributes']['class'] = 'form-range-slider';

    $element['#attached']['library'][] = 'improvements_form/range-slider';

    return $element;
  }

}

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

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