View source
<?php
namespace Drupal\range\Plugin\Field\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
class RangeDecimalFormatter extends RangeIntegerFormatter {
public static function defaultSettings() {
return [
'decimal_separator' => '.',
'scale' => 2,
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['decimal_separator'] = [
'#type' => 'select',
'#title' => $this
->t('Decimal marker'),
'#options' => [
'.' => $this
->t('Decimal point'),
',' => $this
->t('Comma'),
],
'#default_value' => $this
->getSetting('decimal_separator'),
'#weight' => 10,
];
$range = range(0, 10);
$elements['scale'] = [
'#type' => 'select',
'#title' => $this
->t('Scale', [], [
'decimal places',
]),
'#options' => array_combine($range, $range),
'#default_value' => $this
->getSetting('scale'),
'#description' => $this
->t('The number of digits to the right of the decimal.'),
'#weight' => 15,
];
return $elements;
}
protected function formatNumber($number) {
return number_format($number, $this
->getSetting('scale'), $this
->getSetting('decimal_separator'), $this
->getSetting('thousand_separator'));
}
}