Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Field / Plugin / Field / FieldType / FloatItem.php
1 <?php
2
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  * @FieldType(
14  *   id = "float",
15  *   label = @Translation("Number (float)"),
16  *   description = @Translation("This field stores a number in the database in a floating point format."),
17  *   category = @Translation("Number"),
18  *   default_widget = "number",
19  *   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       ->setLabel(t('Float'))
30       ->setRequired(TRUE);
31
32     return $properties;
33   }
34
35   /**
36    * {@inheritdoc}
37    */
38   public static function schema(FieldStorageDefinitionInterface $field_definition) {
39     return [
40       'columns' => [
41         'value' => [
42           'type' => 'float',
43         ],
44       ],
45     ];
46   }
47
48   /**
49    * {@inheritdoc}
50    */
51   public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
52     $element = parent::fieldSettingsForm($form, $form_state);
53
54     $element['min']['#step'] = 'any';
55     $element['max']['#step'] = 'any';
56
57     return $element;
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
64     $settings = $field_definition->getSettings();
65     $precision = rand(10, 32);
66     $scale = rand(0, 2);
67     $max = is_numeric($settings['max']) ?: pow(10, ($precision - $scale)) - 1;
68     $min = is_numeric($settings['min']) ?: -pow(10, ($precision - $scale)) + 1;
69     // @see "Example #1 Calculate a random floating-point number" in
70     // http://php.net/manual/function.mt-getrandmax.php
71     $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
72     $values['value'] = self::truncateDecimal($random_decimal, $scale);
73     return $values;
74   }
75
76 }