3 namespace Drupal\Core\Field\Plugin\Field\FieldWidget;
5 use Drupal\Core\Field\FieldFilteredMarkup;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\WidgetBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\Validator\ConstraintViolationInterface;
12 * Plugin implementation of the 'number' widget.
16 * label = @Translation("Number field"),
24 class NumberWidget extends WidgetBase {
29 public static function defaultSettings() {
32 ] + parent::defaultSettings();
38 public function settingsForm(array $form, FormStateInterface $form_state) {
39 $element['placeholder'] = [
40 '#type' => 'textfield',
41 '#title' => t('Placeholder'),
42 '#default_value' => $this->getSetting('placeholder'),
43 '#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
51 public function settingsSummary() {
54 $placeholder = $this->getSetting('placeholder');
55 if (!empty($placeholder)) {
56 $summary[] = t('Placeholder: @placeholder', ['@placeholder' => $placeholder]);
59 $summary[] = t('No placeholder');
68 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
69 $value = isset($items[$delta]->value) ? $items[$delta]->value : NULL;
70 $field_settings = $this->getFieldSettings();
74 '#default_value' => $value,
75 '#placeholder' => $this->getSetting('placeholder'),
78 // Set the step for floating point and decimal numbers.
79 switch ($this->fieldDefinition->getType()) {
81 $element['#step'] = pow(0.1, $field_settings['scale']);
85 $element['#step'] = 'any';
89 // Set minimum and maximum.
90 if (is_numeric($field_settings['min'])) {
91 $element['#min'] = $field_settings['min'];
93 if (is_numeric($field_settings['max'])) {
94 $element['#max'] = $field_settings['max'];
97 // Add prefix and suffix.
98 if ($field_settings['prefix']) {
99 $prefixes = explode('|', $field_settings['prefix']);
100 $element['#field_prefix'] = FieldFilteredMarkup::create(array_pop($prefixes));
102 if ($field_settings['suffix']) {
103 $suffixes = explode('|', $field_settings['suffix']);
104 $element['#field_suffix'] = FieldFilteredMarkup::create(array_pop($suffixes));
107 return ['value' => $element];
113 public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
114 return $element['value'];