DecimalFormatter.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
  3. use Drupal\Core\Form\FormStateInterface;
  4. /**
  5. * Plugin implementation of the 'number_decimal' formatter.
  6. *
  7. * The 'Default' formatter is different for integer fields on the one hand, and
  8. * for decimal and float fields on the other hand, in order to be able to use
  9. * different settings.
  10. *
  11. * @FieldFormatter(
  12. * id = "number_decimal",
  13. * label = @Translation("Default"),
  14. * field_types = {
  15. * "decimal",
  16. * "float"
  17. * }
  18. * )
  19. */
  20. class DecimalFormatter extends NumericFormatterBase {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public static function defaultSettings() {
  25. return [
  26. 'thousand_separator' => '',
  27. 'decimal_separator' => '.',
  28. 'scale' => 2,
  29. 'prefix_suffix' => TRUE,
  30. ] + parent::defaultSettings();
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function settingsForm(array $form, FormStateInterface $form_state) {
  36. $elements = parent::settingsForm($form, $form_state);
  37. $elements['decimal_separator'] = [
  38. '#type' => 'select',
  39. '#title' => t('Decimal marker'),
  40. '#options' => ['.' => t('Decimal point'), ',' => t('Comma')],
  41. '#default_value' => $this->getSetting('decimal_separator'),
  42. '#weight' => 5,
  43. ];
  44. $elements['scale'] = [
  45. '#type' => 'number',
  46. '#title' => t('Scale', [], ['context' => 'decimal places']),
  47. '#min' => 0,
  48. '#max' => 10,
  49. '#default_value' => $this->getSetting('scale'),
  50. '#description' => t('The number of digits to the right of the decimal.'),
  51. '#weight' => 6,
  52. ];
  53. return $elements;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. protected function numberFormat($number) {
  59. return number_format($number, $this->getSetting('scale'), $this->getSetting('decimal_separator'), $this->getSetting('thousand_separator'));
  60. }
  61. }