You are here

class WebformHeight in Webform 6.x

Same name in this branch
  1. 6.x src/Element/WebformHeight.php \Drupal\webform\Element\WebformHeight
  2. 6.x src/Plugin/WebformElement/WebformHeight.php \Drupal\webform\Plugin\WebformElement\WebformHeight
Same name and namespace in other branches
  1. 8.5 src/Element/WebformHeight.php \Drupal\webform\Element\WebformHeight

Provides a webform height element.

Plugin annotation

@FormElement("webform_height");

Hierarchy

Expanded class hierarchy of WebformHeight

1 file declares its use of WebformHeight
WebformHeight.php in src/Plugin/WebformElement/WebformHeight.php

File

src/Element/WebformHeight.php, line 15

Namespace

Drupal\webform\Element
View source
class WebformHeight extends FormElement {
  use WebformCompositeFormElementTrait;

  /**
   * Denotes height symbol.
   *
   * @var string
   */
  const HEIGHT_SYMBOL = 'symbol';

  /**
   * Denotes height abbreviate.
   *
   * @var string
   */
  const HEIGHT_ABBREVIATE = 'abbreviate';

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#process' => [
        [
          $class,
          'processWebformHeight',
        ],
      ],
      '#pre_render' => [
        [
          $class,
          'preRenderWebformCompositeFormElement',
        ],
      ],
      '#required' => FALSE,
      '#height_type' => 'number',
      '#height_format' => '',
      '#feet__min' => 0,
      '#feet__max' => 8,
      '#inches__step' => 1,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {
      if (!isset($element['#default_value']) || $element['#default_value'] === '') {
        $element['#default_value'] = [
          'feet' => NULL,
          'inches' => NULL,
        ];
      }
      else {
        $value = (double) $element['#default_value'];
        $feet = floor($value / 12);
        $inches = $value - $feet * 12;
        $element['#default_value'] = [
          'feet' => $feet,
          'inches' => $inches,
        ];
      }
      return $element['#default_value'];
    }
    else {
      $element['#default_value'] = $input;
      return $input;
    }
  }

  /**
   * Display feet and inches for height element.
   */
  public static function processWebformHeight(&$element, FormStateInterface $form_state, &$complete_form) {
    switch ($element['#height_format']) {
      case static::HEIGHT_SYMBOL:
        $feet_plural = '″';
        $feet_singular = '″';
        $inches_plural = '′';
        $inches_singular = '′';
        break;
      case static::HEIGHT_ABBREVIATE:
        $feet_plural = t('ft', [], [
          'context' => 'Imperial height unit abbreviate',
        ]);
        $feet_singular = t('ft', [], [
          'context' => 'Imperial height unit abbreviate',
        ]);
        $inches_plural = t('in', [], [
          'context' => 'Imperial height unit abbreviate',
        ]);
        $inches_singular = t('in', [], [
          'context' => 'Imperial height unit abbreviate',
        ]);
        break;
      default:
        $feet_plural = t('feet', [], [
          'context' => 'Imperial height unit',
        ]);
        $feet_singular = t('foot', [], [
          'context' => 'Imperial height unit',
        ]);
        $inches_plural = t('inches', [], [
          'context' => 'Imperial height unit',
        ]);
        $inches_singular = t('inch', [], [
          'context' => 'Imperial height unit',
        ]);
        break;
    }
    $select_element_defaults = [
      '#type' => 'select',
      '#empty_option' => '',
    ];
    $element['#tree'] = TRUE;

    // Feet options.
    $feet_range = range($element['#feet__min'], $element['#feet__max']);
    $feet_options = array_combine($feet_range, $feet_range);

    // Inches options.
    $inches_step = $element['#inches__step'];
    $inches_range = range(0, 11, $inches_step);
    if ($inches_step !== 1 && floor($inches_step) !== $inches_step) {
      $decimals = strlen(substr(strrchr($inches_step, '.'), 1));
      $inches_range = array_map(function ($number) use ($decimals) {
        return number_format($number, $decimals);
      }, $inches_range);
    }
    $inches_options = array_combine($inches_range, $inches_range);

    // Container.
    $element['container'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'form--inline',
        ],
      ],
    ];
    $t_args = [
      '@title' => $element['#title'],
      '@unit' => t('Feet', [], [
        'context' => 'Imperial height unit',
      ]),
    ];
    $element['container']['feet'] = [
      '#title' => t('@title: @unit', $t_args),
      '#title_display' => 'invisible',
      '#required' => $element['#required'],
      '#error_no_message' => TRUE,
      '#default_value' => $element['#default_value']['feet'],
      '#parents' => array_merge($element['#parents'], [
        'feet',
      ]),
    ];
    $t_args = [
      '@title' => $element['#title'],
      '@unit' => t('Inches', [], [
        'context' => 'Imperial height unit',
      ]),
    ];
    $element['container']['inches'] = [
      '#title' => t('@title: @unit', $t_args),
      '#title_display' => 'invisible',
      '#field_prefix' => ' ',
      '#required' => $element['#required'],
      '#error_no_message' => TRUE,
      '#default_value' => $element['#default_value']['inches'],
      '#parents' => array_merge($element['#parents'], [
        'inches',
      ]),
    ];
    switch ($element['#height_type']) {
      case 'select':
        $element['container']['feet'] += $select_element_defaults + [
          '#field_suffix' => $feet_plural,
          '#options' => $feet_options,
        ];
        $element['container']['inches'] += $select_element_defaults + [
          '#field_suffix' => $inches_plural,
          '#options' => $inches_options,
        ];
        break;
      case 'select_suffix':
        foreach ($feet_options as $option_value => $option_text) {
          $feet_options[$option_value] .= ' ' . ($option_value === 1 ? $feet_singular : $feet_plural);
        }
        foreach ($inches_options as $option_value => $option_text) {
          $inches_options[$option_value] .= ' ' . ($option_value === 1 ? $inches_singular : $inches_plural);
        }
        $element['container']['feet'] += $select_element_defaults + [
          '#options' => $feet_options,
        ];
        $element['container']['inches'] += $select_element_defaults + [
          '#options' => $inches_options,
        ];
        break;
      default:
        $element['container']['feet'] += [
          '#type' => 'number',
          '#field_suffix' => $feet_plural,
          '#min' => $element['#feet__min'],
          '#max' => $element['#feet__max'],
          '#step' => 1,
        ];
        $element['container']['inches'] += [
          '#type' => 'number',
          '#field_suffix' => $inches_plural,
          '#min' => 0,
          '#max' => 11,
          '#step' => $inches_step,
        ];
        break;
    }

    // Apply custom properties to feet and inches elements.
    foreach ($element as $key => $value) {
      if (strpos($key, '__') !== FALSE) {
        list($element_key, $property_key) = explode('__', ltrim($key, '#'));
        if (isset($element['container'][$element_key])) {
          $element['container'][$element_key]["#{$property_key}"] = $value;
        }
      }
    }

    // Initialize the feet and inches elements to allow
    // for webform enhancements.

    /** @var \Drupal\webform\Plugin\WebformElementManagerInterface $element_manager */
    $element_manager = \Drupal::service('plugin.manager.webform.element');
    $element_manager
      ->buildElement($element['container']['feet'], $complete_form, $form_state);
    $element_manager
      ->buildElement($element['container']['inches'], $complete_form, $form_state);

    // Add validate callback.
    $element += [
      '#element_validate' => [],
    ];
    array_unshift($element['#element_validate'], [
      get_called_class(),
      'validateWebformHeight',
    ]);
    return $element;
  }

  /**
   * Validates an height element.
   */
  public static function validateWebformHeight(&$element, FormStateInterface $form_state, &$complete_form) {
    $height_element =& $element['container'];
    if ($height_element['feet']['#value'] === '' && $height_element['inches']['#value'] === '') {
      $value = '';
    }
    else {
      $feet = (double) $height_element['feet']['#value'];
      $inches = (double) $height_element['inches']['#value'];
      $value = $feet * 12 + $inches;
    }
    if (Element::isVisibleElement($element) && $element['#required'] && empty($value)) {
      WebformElementHelper::setRequiredError($element, $form_state);
    }
    $form_state
      ->setValueForElement($height_element['feet'], NULL);
    $form_state
      ->setValueForElement($height_element['inches'], NULL);
    $value = (string) $value;
    $element['#value'] = $value;
    $form_state
      ->setValueForElement($element, $value);
  }

}

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
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 98
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
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.
WebformCompositeFormElementTrait::preRenderWebformCompositeFormElement public static function Adds form element theming to an element if its title or description is set. 1
WebformHeight::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
WebformHeight::HEIGHT_ABBREVIATE constant Denotes height abbreviate.
WebformHeight::HEIGHT_SYMBOL constant Denotes height symbol.
WebformHeight::processWebformHeight public static function Display feet and inches for height element.
WebformHeight::validateWebformHeight public static function Validates an height element.
WebformHeight::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback