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;
14 * Defines the 'field_test' entity field type.
18 * label = @Translation("Test field item"),
19 * description = @Translation("A field containing a plain string value."),
20 * category = @Translation("Field"),
23 class FieldTestItem extends FieldItemBase {
26 * Counts how many times all items of this type are saved.
30 protected static $counter = [];
35 public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
36 // This is called very early by the user entity roles field. Prevent
37 // early t() calls by using the TranslatableMarkup.
38 $properties['value'] = DataDefinition::create('string')
39 ->setLabel(new TranslatableMarkup('Test value'))
48 public static function schema(FieldStorageDefinitionInterface $field_definition) {
62 public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
63 parent::__construct($definition, $name, $parent);
65 $name = $this->getFieldDefinition()->getName();
66 static::$counter[$name] = 0;
72 public function preSave() {
73 $name = $this->getFieldDefinition()->getName();
74 static::$counter[$name]++;
76 // Overwrite the field value unless it is going to be overridden, in which
77 // case its final value will already be different from the current one.
78 if (!$this->getEntity()->isNew() && !$this->mustResave()) {
79 $this->setValue('overwritten');
86 public function postSave($update) {
87 // Determine whether the field value should be rewritten to the storage. We
88 // always rewrite on create as we need to store a value including the entity
90 $resave = !$update || $this->mustResave();
93 $entity = $this->getEntity();
94 $definition = $this->getFieldDefinition();
95 $name = $definition->getName();
96 $value = 'field_test:' . $name . ':' . $entity->id() . ':' . static::$counter[$name];
97 $this->setValue($value);
104 * Checks whether the field item value should be resaved.
107 * TRUE if the item should be resaved, FALSE otherwise.
109 protected function mustResave() {
110 return $this->getValue()['value'] == 'resave';
116 public function delete() {
118 $deleted_languages = \Drupal::state()->get('entity_test.delete.' . $this->getFieldDefinition()->getName()) ?: [];
119 $deleted_languages[] = $this->getLangcode();
120 \Drupal::state()->set('entity_test.delete.' . $this->getFieldDefinition()->getName(), $deleted_languages);