ComputedIntegerItem.php in Computed Field 8.2
File
src/Plugin/Field/FieldType/ComputedIntegerItem.php
View source
<?php
namespace Drupal\computed_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
class ComputedIntegerItem extends ComputedFieldItemBase {
public static function defaultStorageSettings() {
return [
'unsigned' => FALSE,
'size' => 'normal',
] + parent::defaultStorageSettings();
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
->setLabel(new TranslatableMarkup('Integer value'))
->setRequired(TRUE);
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$settings = $field_definition
->getSettings();
$schema = [
'columns' => [
'value' => [
'type' => 'int',
'size' => $settings['size'],
],
],
];
return $schema;
}
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$values['value'] = rand(PHP_INT_MIN, PHP_INT_MAX);
return $values;
}
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = parent::fieldSettingsForm($form, $form_state);
$element['code']['#title'] = $this
->t('Code (PHP) to compute the <em>integer</em> value');
$element['code']['#description'] .= '<p>' . t('The value will be rounded to an integer value.') . '</p>';
return $element;
}
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
return [];
}
public function executeCode() {
return (int) parent::executeCode();
}
}