FieldTestItem.php in Drupal 9
File
core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/FieldTestItem.php
View source
<?php
namespace Drupal\entity_test\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataInterface;
class FieldTestItem extends FieldItemBase {
protected static $counter = [];
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Test value'))
->setRequired(TRUE);
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'varchar',
'length' => 255,
],
],
];
}
public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
parent::__construct($definition, $name, $parent);
$name = $this
->getFieldDefinition()
->getName();
static::$counter[$name] = 0;
}
public function preSave() {
$name = $this
->getFieldDefinition()
->getName();
static::$counter[$name]++;
if (!$this
->getEntity()
->isNew() && !$this
->mustResave()) {
$this
->setValue('overwritten');
}
}
public function postSave($update) {
$resave = !$update || $this
->mustResave();
if ($resave) {
$entity = $this
->getEntity();
$definition = $this
->getFieldDefinition();
$name = $definition
->getName();
$value = 'field_test:' . $name . ':' . $entity
->id() . ':' . static::$counter[$name];
$this
->setValue($value);
}
return $resave;
}
protected function mustResave() {
return $this
->getValue()['value'] == 'resave';
}
public function delete() {
parent::delete();
$deleted_languages = \Drupal::state()
->get('entity_test.delete.' . $this
->getFieldDefinition()
->getName(), []);
$deleted_languages[] = $this
->getLangcode();
\Drupal::state()
->set('entity_test.delete.' . $this
->getFieldDefinition()
->getName(), $deleted_languages);
}
}