3 namespace Drupal\{{ machine_name }}\Plugin\Field\FieldType;
5 use Drupal\Component\Utility\Random;
6 use Drupal\Core\Field\FieldDefinitionInterface;
7 use Drupal\Core\Field\FieldItemBase;
8 use Drupal\Core\Field\FieldStorageDefinitionInterface;
9 {% if configurable_storage or configurable_instance %}
10 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\TypedData\DataDefinition;
15 * Defines the '{{ plugin_id }}' field type.
18 * id = "{{ plugin_id }}",
19 * label = @Translation("{{ plugin_label }}"),
20 * category = @Translation("General"),
21 * default_widget = "string_textfield",
22 * default_formatter = "string"
26 * If you are implementing a single value field type you may want to inherit
27 * this class form some of the field type classes provided by Drupal core.
28 * Check out /core/lib/Drupal/Core/Field/Plugin/Field/FieldType directory for a
29 * list of available field type implementations.
31 class {{ class }} extends FieldItemBase {
33 {% if configurable_storage %}
37 public static function defaultStorageSettings() {
38 $settings = ['foo' => 'wine'];
39 return $settings + parent::defaultStorageSettings();
45 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
48 '#type' => 'textfield',
49 '#title' => $this->t('Foo'),
50 '#default_value' => $this->getSetting('foo'),
51 '#disabled' => $has_data,
58 {% if configurable_instance %}
62 public static function defaultFieldSettings() {
63 $settings = ['bar' => 'beer'];
64 return $settings + parent::defaultFieldSettings();
70 public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
73 '#type' => 'textfield',
75 '#default_value' => $this->getSetting('bar'),
85 public function isEmpty() {
86 $value = $this->get('value')->getValue();
87 return $value === NULL || $value === '';
93 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
96 // See /core/lib/Drupal/Core/TypedData/Plugin/DataType directory for
97 // available data types.
98 $properties['value'] = DataDefinition::create('string')
99 ->setLabel(t('Text value'))
108 public function getConstraints() {
109 $constraints = parent::getConstraints();
111 $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
113 // @DCG Suppose our value must not be longer than 10 characters.
114 $options['value']['Length']['max'] = 10;
117 // See /core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint
118 // directory for available constraints.
119 $constraints[] = $constraint_manager->create('ComplexData', $options);
126 public static function schema(FieldStorageDefinitionInterface $field_definition) {
132 'description' => 'Column description.',
138 'columns' => $columns,
139 // @DCG Add indexes here if necessary.
148 public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
149 $random = new Random();
150 $values['value'] = $random->word(mt_rand(1, 50));