|
<?php |
|
|
|
namespace Drupal\my_module\Plugin\Field\FieldType; |
|
|
|
use Drupal\Core\Entity\TypedData\EntityDataDefinition; |
|
use Drupal\Core\Field\FieldItemBase; |
|
use Drupal\Core\Field\FieldStorageDefinitionInterface; |
|
use Drupal\Core\TypedData\DataDefinition; |
|
use Drupal\Core\TypedData\DataReferenceDefinition; |
|
use Drupal\user\Entity\User; |
|
|
|
/** |
|
* Provides a field type of author. |
|
* |
|
* @FieldType( |
|
* id="author", |
|
* label=@Translation("Author"), |
|
* module="my_module", |
|
* description=@Translation("A field to define an Author."), |
|
* default_formatter="author_default", |
|
* default_widget="author_default", |
|
* ) |
|
*/ |
|
class AuthorItem extends FieldItemBase { |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public function isEmpty(): bool { |
|
$fullname = $this->get('fullname')->getValue(); |
|
$user_id = $this->get('user_id')->getValue(); |
|
|
|
return $fullname === NULL || $fullname === '' || $user_id === NULL || $user_id === ''; |
|
} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition): array { |
|
$properties = []; |
|
|
|
$properties['fullname'] = DataDefinition::create('string') |
|
->setLabel(t('Fullname')->__toString()); |
|
|
|
$properties['user_id'] = DataDefinition::create('integer') |
|
->setLabel(t('The Author ID')->__toString()); |
|
|
|
$properties['user'] = DataReferenceDefinition::create('entity') |
|
->setLabel(t('The Author entity')->__toString()) |
|
// The entity object is computed out of the entity ID. |
|
->setComputed(TRUE) |
|
->setTargetDefinition(EntityDataDefinition::create('user')) |
|
->addConstraint('EntityType', 'user') |
|
->addConstraint('Bundle', 'user'); |
|
|
|
return $properties; |
|
} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public function setValue($values, $notify = TRUE) { |
|
parent::setValue($values, FALSE); |
|
|
|
// Populate the computed "user" property. |
|
if (\is_array($values) && \array_key_exists('user_id', $values)) { |
|
$this->set('user', User::load($values['user_id']), $notify); |
|
} |
|
} |
|
|
|
/** |
|
* {@inheritdoc} |
|
*/ |
|
public static function schema(FieldStorageDefinitionInterface $field_definition): array { |
|
return [ |
|
// Columns contains the values that the field will store. |
|
'columns' => [ |
|
'fullname' => [ |
|
'type' => 'text', |
|
'size' => 'tiny', |
|
'not null' => FALSE, |
|
], |
|
'user_id' => [ |
|
'type' => 'int', |
|
'description' => 'The ID of the user entity.', |
|
'unsigned' => TRUE, |
|
], |
|
], |
|
'indexes' => [ |
|
'user_id' => ['user_id'], |
|
], |
|
]; |
|
} |
|
|
|
} |