FloatItem.php 2.06 KB
Newer Older
1 2
<?php

3
namespace Drupal\Core\Field\Plugin\Field\FieldType;
4

5
use Drupal\Core\Field\FieldDefinitionInterface;
6
use Drupal\Core\Field\FieldStorageDefinitionInterface;
7
use Drupal\Core\Form\FormStateInterface;
8
use Drupal\Core\TypedData\DataDefinition;
9 10

/**
11
 * Defines the 'float' field type.
12
 *
13 14
 * @FieldType(
 *   id = "float",
15 16
 *   label = @Translation("Number (float)"),
 *   description = @Translation("This field stores a number in the database in a floating point format."),
17
 *   category = @Translation("Number"),
18 19
 *   default_widget = "number",
 *   default_formatter = "number_decimal"
20 21
 * )
 */
22
class FloatItem extends NumericItemBase {
23 24

  /**
25
   * {@inheritdoc}
26
   */
27
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
28
    $properties['value'] = DataDefinition::create('float')
29 30
      ->setLabel(t('Float'))
      ->setRequired(TRUE);
31

32
    return $properties;
33
  }
34 35 36 37

  /**
   * {@inheritdoc}
   */
38
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
39 40 41
    return [
      'columns' => [
        'value' => [
42
          'type' => 'float',
43 44 45
        ],
      ],
    ];
46 47
  }

48 49 50 51 52 53 54 55 56 57 58 59
  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $element = parent::fieldSettingsForm($form, $form_state);

    $element['min']['#step'] = 'any';
    $element['max']['#step'] = 'any';

    return $element;
  }

60 61 62 63 64 65 66 67 68 69
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $settings = $field_definition->getSettings();
    $precision = rand(10, 32);
    $scale = rand(0, 2);
    $max = is_numeric($settings['max']) ?: pow(10, ($precision - $scale)) - 1;
    $min = is_numeric($settings['min']) ?: -pow(10, ($precision - $scale)) + 1;
    // @see "Example #1 Calculate a random floating-point number" in
70
    // http://php.net/manual/function.mt-getrandmax.php
71 72 73 74 75
    $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    $values['value'] = self::truncateDecimal($random_decimal, $scale);
    return $values;
  }

76
}