You are here

class Number in Price 3.0.x

Same name and namespace in other branches
  1. 8 src/Element/Number.php \Drupal\price\Element\Number
  2. 3.x src/Element/Number.php \Drupal\price\Element\Number
  3. 2.0.x src/Element/Number.php \Drupal\price\Element\Number
  4. 2.x src/Element/Number.php \Drupal\price\Element\Number

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' => 'price_number',
  '#title' => t('Number'),
  '#default_value' => '18.99',
  '#required' => TRUE,
];

Plugin annotation

@FormElement("price_number");

Hierarchy

Expanded class hierarchy of Number

1 string reference to 'Number'
price.schema.yml in config/schema/price.schema.yml
config/schema/price.schema.yml
2 #type uses of Number
Price::processElement in src/Element/Price.php
Builds the price_price form element.
PriceModified::processElement in src/Element/PriceModified.php
Builds the price_price form element.

File

src/Element/Number.php, line 29

Namespace

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

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#min_fraction_digits' => 0,
      '#max_fraction_digits' => 6,
      '#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('price.number_formatter');
      $number = (string) $element['#default_value'];
      $number = $number_formatter
        ->format($number, [
        'use_grouping' => FALSE,
        'minimum_fraction_digits' => $element['#min_fraction_digits'],
        'maximum_fraction_digits' => $element['#max_fraction_digits'],
      ]);
      return $number;
    }
    return NULL;
  }

  /**
   * Builds the price_number form element.
   *
   * @param array $element
   *   The initial price_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 price_number form element.
   */
  public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {

    // Add a sensible default AJAX event.
    if (isset($element['#ajax']) && !isset($element['#ajax']['event'])) {
      $element['#ajax']['event'] = 'blur';
    }

    // 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('price.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('price.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 'price_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
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.
Number::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
Number::preRenderNumber public static function Prepares a #type 'price_number' render element for input.html.twig.
Number::processElement public static function Builds the price_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 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.