Skip to content

Instantly share code, notes, and snippets.

@jodyHamilton
Created April 20, 2017 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jodyHamilton/e435f217e2e48ca2d32526405be0685e to your computer and use it in GitHub Desktop.
Save jodyHamilton/e435f217e2e48ca2d32526405be0685e to your computer and use it in GitHub Desktop.
Drupal 8 number field widget that uses commas to separate thousands
<?php
namespace Drupal\YourModule\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\NumberWidget;
/**
* Plugin implementation of the 'number' widget.
*
* @FieldWidget(
* id = "number_with_commas",
* label = @Translation("Number with commas field"),
* field_types = {
* "integer",
* "decimal",
* "float"
* }
* )
*/
class NumberCommasWidget extends NumberWidget {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : NULL;
$field_settings = $this->getFieldSettings();
// Use a textfield instead of a number field for this widget.
// Preserve the number of decimal places, but add commas to numbers.
$element += array(
'#type' => 'textfield',
'#default_value' => number_format($value, strlen(substr(strrchr($value, "."), 1)), '.', ','),
'#placeholder' => $this->getSetting('placeholder'),
);
// Set minimum and maximum.
if (is_numeric($field_settings['min'])) {
$element['#min'] = $field_settings['min'];
}
if (is_numeric($field_settings['max'])) {
$element['#max'] = $field_settings['max'];
}
// Add prefix and suffix.
if ($field_settings['prefix']) {
$prefixes = explode('|', $field_settings['prefix']);
$element['#field_prefix'] = FieldFilteredMarkup::create(array_pop($prefixes));
}
if ($field_settings['suffix']) {
$suffixes = explode('|', $field_settings['suffix']);
$element['#field_suffix'] = FieldFilteredMarkup::create(array_pop($suffixes));
}
return array('value' => $element);
}
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
// Remove commas from numbers.
foreach ($values as &$value) {
$value = str_replace(',', '', $value);
}
return $values;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment