3 namespace Drupal\Core\Field\Plugin\Field\FieldType;
5 use Drupal\Core\Field\FieldItemBase;
6 use Drupal\Core\Form\FormStateInterface;
9 * Base class for numeric configurable field types.
11 abstract class NumericItemBase extends FieldItemBase {
16 public static function defaultFieldSettings() {
22 ] + parent::defaultFieldSettings();
28 public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
30 $settings = $this->getSettings();
34 '#title' => t('Minimum'),
35 '#default_value' => $settings['min'],
36 '#description' => t('The minimum value that should be allowed in this field. Leave blank for no minimum.'),
40 '#title' => t('Maximum'),
41 '#default_value' => $settings['max'],
42 '#description' => t('The maximum value that should be allowed in this field. Leave blank for no maximum.'),
44 $element['prefix'] = [
45 '#type' => 'textfield',
46 '#title' => t('Prefix'),
47 '#default_value' => $settings['prefix'],
49 '#description' => t("Define a string that should be prefixed to the value, like '$ ' or '€ '. Leave blank for none. Separate singular and plural values with a pipe ('pound|pounds')."),
51 $element['suffix'] = [
52 '#type' => 'textfield',
53 '#title' => t('Suffix'),
54 '#default_value' => $settings['suffix'],
56 '#description' => t("Define a string that should be suffixed to the value, like ' m', ' kb/s'. Leave blank for none. Separate singular and plural values with a pipe ('pound|pounds')."),
65 public function isEmpty() {
66 if (empty($this->value) && (string) $this->value !== '0') {
75 public function getConstraints() {
76 $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
77 $constraints = parent::getConstraints();
79 $settings = $this->getSettings();
80 $label = $this->getFieldDefinition()->getLabel();
82 if (!empty($settings['min'])) {
83 $min = $settings['min'];
84 $constraints[] = $constraint_manager->create('ComplexData', [
88 'minMessage' => t('%name: the value may be no less than %min.', ['%name' => $label, '%min' => $min]),
94 if (!empty($settings['max'])) {
95 $max = $settings['max'];
96 $constraints[] = $constraint_manager->create('ComplexData', [
100 'maxMessage' => t('%name: the value may be no greater than %max.', ['%name' => $label, '%max' => $max]),
110 * Helper method to truncate a decimal number to a given number of decimals.
112 * @param float $decimal
113 * Decimal number to truncate.
115 * Number of digits the output will have.
118 * Decimal number truncated.
120 protected static function truncateDecimal($decimal, $num) {
121 return floor($decimal * pow(10, $num)) / pow(10, $num);