3 namespace Drupal\entity_test\Plugin\Field\FieldType;
5 use Drupal\Core\Field\FieldItemBase;
6 use Drupal\Core\Field\FieldStorageDefinitionInterface;
7 use Drupal\Core\StringTranslation\TranslatableMarkup;
8 use Drupal\Core\TypedData\DataDefinition;
9 use Drupal\Core\TypedData\DataDefinitionInterface;
10 use Drupal\Core\TypedData\TypedDataInterface;
13 * Defines the 'field_test' entity field type.
17 * label = @Translation("Test field item"),
18 * description = @Translation("A field containing a plain string value."),
19 * category = @Translation("Field"),
22 class FieldTestItem extends FieldItemBase {
25 * Counts how many times all items of this type are saved.
29 protected static $counter = [];
34 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
35 // This is called very early by the user entity roles field. Prevent
36 // early t() calls by using the TranslatableMarkup.
37 $properties['value'] = DataDefinition::create('string')
38 ->setLabel(new TranslatableMarkup('Test value'))
47 public static function schema(FieldStorageDefinitionInterface $field_definition) {
61 public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
62 parent::__construct($definition, $name, $parent);
64 $name = $this->getFieldDefinition()->getName();
65 static::$counter[$name] = 0;
71 public function preSave() {
72 $name = $this->getFieldDefinition()->getName();
73 static::$counter[$name]++;
75 // Overwrite the field value unless it is going to be overridden, in which
76 // case its final value will already be different from the current one.
77 if (!$this->getEntity()->isNew() && !$this->mustResave()) {
78 $this->setValue('overwritten');
85 public function postSave($update) {
86 // Determine whether the field value should be rewritten to the storage. We
87 // always rewrite on create as we need to store a value including the entity
89 $resave = !$update || $this->mustResave();
92 $entity = $this->getEntity();
93 $definition = $this->getFieldDefinition();
94 $name = $definition->getName();
95 $value = 'field_test:' . $name . ':' . $entity->id() . ':' . static::$counter[$name];
96 $this->setValue($value);
103 * Checks whether the field item value should be resaved.
106 * TRUE if the item should be resaved, FALSE otherwise.
108 protected function mustResave() {
109 return $this->getValue()['value'] == 'resave';
115 public function delete() {
117 $deleted_languages = \Drupal::state()->get('entity_test.delete.' . $this->getFieldDefinition()->getName()) ?: [];
118 $deleted_languages[] = $this->getLangcode();
119 \Drupal::state()->set('entity_test.delete.' . $this->getFieldDefinition()->getName(), $deleted_languages);