View source
<?php
namespace Drupal\Core\Field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Form\FormStateInterface;
abstract class NumericItemBase extends FieldItemBase {
public static function defaultFieldSettings() {
return [
'min' => '',
'max' => '',
'prefix' => '',
'suffix' => '',
] + parent::defaultFieldSettings();
}
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$settings = $this
->getSettings();
$element['min'] = [
'#type' => 'number',
'#title' => t('Minimum'),
'#default_value' => $settings['min'],
'#description' => t('The minimum value that should be allowed in this field. Leave blank for no minimum.'),
];
$element['max'] = [
'#type' => 'number',
'#title' => t('Maximum'),
'#default_value' => $settings['max'],
'#description' => t('The maximum value that should be allowed in this field. Leave blank for no maximum.'),
];
$element['prefix'] = [
'#type' => 'textfield',
'#title' => t('Prefix'),
'#default_value' => $settings['prefix'],
'#size' => 60,
'#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')."),
];
$element['suffix'] = [
'#type' => 'textfield',
'#title' => t('Suffix'),
'#default_value' => $settings['suffix'],
'#size' => 60,
'#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')."),
];
return $element;
}
public function isEmpty() {
if (empty($this->value) && (string) $this->value !== '0') {
return TRUE;
}
return FALSE;
}
public function getConstraints() {
$constraint_manager = \Drupal::typedDataManager()
->getValidationConstraintManager();
$constraints = parent::getConstraints();
$settings = $this
->getSettings();
$label = $this
->getFieldDefinition()
->getLabel();
if (isset($settings['min']) && $settings['min'] !== '') {
$min = $settings['min'];
$constraints[] = $constraint_manager
->create('ComplexData', [
'value' => [
'Range' => [
'min' => $min,
'minMessage' => t('%name: the value may be no less than %min.', [
'%name' => $label,
'%min' => $min,
]),
],
],
]);
}
if (isset($settings['max']) && $settings['max'] !== '') {
$max = $settings['max'];
$constraints[] = $constraint_manager
->create('ComplexData', [
'value' => [
'Range' => [
'max' => $max,
'maxMessage' => t('%name: the value may be no greater than %max.', [
'%name' => $label,
'%max' => $max,
]),
],
],
]);
}
return $constraints;
}
protected static function truncateDecimal($decimal, $num) {
return floor($decimal * pow(10, $num)) / pow(10, $num);
}
}