You are here

class UnlimitedNumber in Unlimited Number Field 2.x

Same name and namespace in other branches
  1. 8 src/Element/UnlimitedNumber.php \Drupal\unlimited_number\Element\UnlimitedNumber

Provides an unlimited or number radios element

Properties:

  • #default_value: A integer or the value of UnlimitedNumber::UNLIMITED.
  • #min: Minimum value.
  • #max: Maximum value.
  • #step: Number stepping, using #min as a base value.
  • #options:
    • unlimited: Label for unlimited radio.
    • limited: Label for limited radio.

Plugin annotation

@FormElement("unlimited_number");

Hierarchy

Expanded class hierarchy of UnlimitedNumber

1 file declares its use of UnlimitedNumber
UnlimitedNumberWidget.php in src/Plugin/Field/FieldWidget/UnlimitedNumberWidget.php
1 #type use of UnlimitedNumber
UnlimitedNumberWidget::formElement in src/Plugin/Field/FieldWidget/UnlimitedNumberWidget.php
Returns the form for a single field widget.

File

src/Element/UnlimitedNumber.php, line 22

Namespace

Drupal\unlimited_number\Element
View source
class UnlimitedNumber extends FormElement {

  /**
   * String returned by the element if the unlimited radio is checked.
   */
  const UNLIMITED = 'unlimited';

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#process' => [
        [
          $class,
          'processUnlimitedNumber',
        ],
      ],
      '#element_validate' => [
        [
          $class,
          'validateUnlimitedNumber',
        ],
      ],
    ];
  }

  /**
   * Adds form fields for radios and number field.
   *
   * @return array
   *   The processed element.
   */
  public static function processUnlimitedNumber(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
    $element['unlimited_number'] = [
      '#type' => 'radios',
      '#options' => NULL,
      '#title' => $element['#title'],
      '#description' => $element['#description'],
      '#required' => !empty($element['#required']),
      // Kills \Drupal\Core\Render\Element\Radios::processRadios.
      '#process' => [],
    ];
    $element['unlimited_number']['unlimited'] = [
      '#prefix' => '<div class="form-item">',
      '#suffix' => '</div>',
    ];
    $element['unlimited_number']['unlimited']['radio'] = [
      '#type' => 'radio',
      '#title' => !empty($element['#options']['unlimited']) ? $element['#options']['unlimited'] : t('Unlimited'),
      '#return_value' => 'unlimited',
      '#parents' => array_merge($element['#parents'], [
        'unlimited_number',
      ]),
      '#default_value' => $value == static::UNLIMITED ? 'unlimited' : NULL,
      // Errors only on parent.
      '#error_no_message' => TRUE,
      '#attributes' => $element['#attributes'],
      '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
    ];
    $element['unlimited_number']['limited'] = [
      '#prefix' => '<div class="form-item container-inline">',
      '#suffix' => '</div>',
    ];
    $element['unlimited_number']['limited']['radio'] = [
      '#type' => 'radio',
      '#title' => !empty($element['#options']['limited']) ? $element['#options']['limited'] : t('Limited'),
      '#return_value' => 'limited',
      '#parents' => array_merge($element['#parents'], [
        'unlimited_number',
      ]),
      '#default_value' => is_numeric($value) ? 'limited' : NULL,
      '#error_no_message' => TRUE,
      '#attributes' => $element['#attributes'],
      '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
    ];
    $element['unlimited_number']['limited']['number'] = [
      '#type' => 'number',
      '#parents' => array_merge($element['#parents'], [
        'number',
      ]),
      '#default_value' => is_numeric($value) ? $value : NULL,
      '#field_prefix' => isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL,
      '#field_suffix' => isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL,
      '#min' => isset($element['#min']) ? $element['#min'] : NULL,
      '#max' => isset($element['#max']) ? $element['#max'] : NULL,
      '#step' => isset($element['#step']) ? $element['#step'] : NULL,
      '#attributes' => $element['#attributes'],
      '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
    ];

    // Must be a tree otherwise the last processed child element will leak its
    // value down to the root element.
    $element['#tree'] = TRUE;

    // Prevent entire tree being required. Fixes empty number field adding
    // errors to the entire tree.
    $element['#required'] = FALSE;

    // Unset options as they are not valid radios.
    unset($element['#options']);
    return $element;
  }

  /**
   * Form element validation handler for unlimited_number elements.
   *
   * @see getInfo().
   */
  public static function validateUnlimitedNumber(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $value = NULL;
    if ($element['unlimited_number']['#value'] == 'unlimited') {
      $value = static::UNLIMITED;
    }
    else {
      if ($element['unlimited_number']['#value'] == 'limited') {

        // If limited radio is checked, number field is required.
        $limited = $element['unlimited_number']['limited']['number']['#value'];
        if (is_numeric($limited)) {
          $value = $limited;
        }
        else {
          $form_state
            ->setError($element['unlimited_number']['limited']['number'], t('A number must be entered. Otherwise choose @unlimited.', [
            '@unlimited' => $element['unlimited_number']['unlimited']['radio']['#title'],
          ]));
        }
      }
    }
    $form_state
      ->setValueForElement($element, $value);
  }

  /**
   * {@inheritdoc}
   *
   * Maps to $form[$element]['#value'], not $form_state->getValue('element').
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input !== FALSE && $input !== NULL) {
      if (!empty($input['unlimited_number'])) {
        if ($input['unlimited_number'] == 'unlimited') {
          return static::UNLIMITED;
        }
        else {
          return $input['number'];
        }
      }
    }

    // For a NULL default value, set #has_garbage_value.
    // @see \Drupal\Core\Render\Element\Radios
    $element['#has_garbage_value'] = TRUE;
    return NULL;
  }

}

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.
UnlimitedNumber::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
UnlimitedNumber::processUnlimitedNumber public static function Adds form fields for radios and number field.
UnlimitedNumber::UNLIMITED constant String returned by the element if the unlimited radio is checked.
UnlimitedNumber::validateUnlimitedNumber public static function Form element validation handler for unlimited_number elements.
UnlimitedNumber::valueCallback public static function Maps to $form[$element]['#value'], not $form_state->getValue('element'). Overrides FormElement::valueCallback