View source
<?php
namespace Drupal\key_value_field\Plugin\Field\FieldType;
use Drupal\Component\Utility\Random;
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;
trait KeyValueFieldTypeTrait {
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = parent::schema($field_definition);
$schema['indexes']['key'] = [
'key',
];
$schema['columns'] += [
'key' => [
'description' => 'Stores the "Key" value.',
'type' => $field_definition
->getSetting('key_is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
'length' => (int) $field_definition
->getSetting('key_max_length'),
],
'description' => [
'description' => 'Stores an optional description of the field.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
],
];
return $schema;
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
return [
'key' => DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Key'))
->setRequired(TRUE),
'description' => DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Description'))
->setRequired(FALSE),
] + parent::propertyDefinitions($field_definition);
}
public static function defaultStorageSettings() {
return [
'key_max_length' => 255,
'key_is_ascii' => FALSE,
] + parent::defaultStorageSettings();
}
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
return [
'key_max_length' => [
'#type' => 'number',
'#title' => t('Key maximum length'),
'#default_value' => $this
->getSetting('key_max_length'),
'#required' => TRUE,
'#description' => t('The maximum length of the "key" field in characters.'),
'#min' => 1,
'#disabled' => $has_data,
],
] + parent::storageSettingsForm($form, $form_state, $has_data);
}
public function isEmpty() {
$key = $this
->get('key')
->getValue();
return ($key === NULL || $key === '') && parent::isEmpty();
}
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$random = new Random();
return [
'key' => $random
->word(mt_rand(1, $field_definition
->getSetting('key_max_length'))),
'description' => $random
->word(mt_rand(1, 255)),
] + parent::generateSampleValue($field_definition);
}
}