You are here

class Number in Physical Fields 8

Provides a number form element with support for language-specific input.

The #default_value is given in the generic, language-agnostic format, which is then formatted into the language-specific format on element display. During element validation the input is converted back into to the generic format, to allow the returned value to be stored.

Usage example:

$form['number'] = [
  '#type' => 'physical_number',
  '#title' => t('Number'),
  '#default_value' => '18.99',
  '#required' => TRUE,
];

Plugin annotation

@FormElement("physical_number");

Hierarchy

Expanded class hierarchy of Number

2 string references to 'Number'
MeasurementItem::propertyDefinitions in src/Plugin/Field/FieldType/MeasurementItem.php
Defines field item properties.
physical.schema.yml in config/schema/physical.schema.yml
config/schema/physical.schema.yml
2 #type uses of Number
Dimensions::processElement in src/Element/Dimensions.php
Builds the physical_dimensions form element.
Measurement::processElement in src/Element/Measurement.php
Builds the physical_measurement form element.

File

src/Element/Number.php, line 29

Namespace

Drupal\physical\Element
View source
class Number extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#min' => 0,
      '#max' => NULL,
      '#size' => 10,
      '#maxlength' => 128,
      '#default_value' => NULL,
      '#element_validate' => [
        [
          $class,
          'validateNumber',
        ],
      ],
      '#process' => [
        [
          $class,
          'processElement',
        ],
        [
          $class,
          'processAjaxForm',
        ],
        [
          $class,
          'processGroup',
        ],
      ],
      '#pre_render' => [
        [
          $class,
          'preRenderNumber',
        ],
        [
          $class,
          'preRenderGroup',
        ],
      ],
      '#input' => TRUE,
      '#theme' => 'input__textfield',
      '#theme_wrappers' => [
        'form_element',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input !== FALSE && $input !== NULL) {
      if (!is_scalar($input)) {
        $input = '';
      }
      return trim($input);
    }
    elseif (!empty($element['#default_value'])) {

      // Convert the stored number to the local format. For example, "9.99"
      // becomes "9,99" in many locales. This also strips any extra zeroes.
      $number_formatter = \Drupal::service('physical.number_formatter');
      return $number_formatter
        ->format($element['#default_value']);
    }
    return NULL;
  }

  /**
   * Builds the physical_number form element.
   *
   * @param array $element
   *   The initial physical_number form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   *
   * @return array
   *   The built physical_number form element.
   */
  public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {

    // Provide an example to the end user so that they know which decimal
    // separator to use. This is the same pattern Drupal core uses.
    $number_formatter = \Drupal::service('physical.number_formatter');
    $element['#placeholder'] = $number_formatter
      ->format('9.99');
    return $element;
  }

  /**
   * Validates the number element.
   *
   * Converts the number back to the standard format (e.g. "9,99" -> "9.99").
   *
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public static function validateNumber(array $element, FormStateInterface $form_state) {
    $value = trim($element['#value']);
    if ($value === '') {
      return;
    }
    $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
    $number_formatter = \Drupal::service('physical.number_formatter');
    $value = $number_formatter
      ->parse($value);
    if ($value === FALSE) {
      $form_state
        ->setError($element, t('%title must be a number.', [
        '%title' => $title,
      ]));
      return;
    }
    if (isset($element['#min']) && $value < $element['#min']) {
      $form_state
        ->setError($element, t('%title must be higher than or equal to %min.', [
        '%title' => $title,
        '%min' => $element['#min'],
      ]));
      return;
    }
    if (isset($element['#max']) && $value > $element['#max']) {
      $form_state
        ->setError($element, t('%title must be lower than or equal to %max.', [
        '%title' => $title,
        '%max' => $element['#max'],
      ]));
      return;
    }
    $form_state
      ->setValueForElement($element, $value);
  }

  /**
   * Prepares a #type 'physical_number' render element for input.html.twig.
   *
   * @param array $element
   *   An associative array containing the properties of the element.
   *   Properties used: #title, #value, #description, #size, #maxlength,
   *   #placeholder, #required, #attributes.
   *
   * @return array
   *   The $element with prepared variables ready for input.html.twig.
   */
  public static function preRenderNumber(array $element) {

    // We're not using the "number" type because it won't accept
    // language-specific input, such as commas.
    $element['#attributes']['type'] = 'text';
    Element::setAttributes($element, [
      'id',
      'name',
      'value',
      'size',
      'maxlength',
      'placeholder',
    ]);
    static::setAttributes($element, [
      'form-text',
    ]);
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
Number::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
Number::preRenderNumber public static function Prepares a #type 'physical_number' render element for input.html.twig.
Number::processElement public static function Builds the physical_number form element.
Number::validateNumber public static function Validates the number element.
Number::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback
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 3
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. 92
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. 1
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.