Skip to content

Instantly share code, notes, and snippets.

@WengerK
Created April 12, 2023 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WengerK/b59e6b478c00eb81b15f0dd7d332e0c9 to your computer and use it in GitHub Desktop.
Save WengerK/b59e6b478c00eb81b15f0dd7d332e0c9 to your computer and use it in GitHub Desktop.
Article Ressources - How to create an Entity Field Widget Autocomplete for Internal Data on Drupal

Article Ressources - How to create an Entity Field Widget Autocomplete for Internal Data on Drupal

This is the Gist repository for my article How to create an Entity Field Widget Autocomplete for Internal Data on Drupal.

Be aware that this article has been wrote for the Blog of Antistatique — Web Agency in Lausanne, Switzerland. A place where I work as Full Stack Web Developer.

Feel free to read it the full article on Medium or check it out on Antistatique.

<?php
namespace Drupal\my_module\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'author_default' widget.
*
* @FieldWidget(
* id="author_default",
* label=@Translation("Default"),
* field_types={
* "author"
* }
* )
*/
class AuthorDefaultWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['fullname'] = [
'#title' => $this->t('Fullname'),
'#type' => 'textfield',
'#default_value' => $items[$delta]->fullname ?? NULL,
];
$element['user_id'] = [
'#type' => 'entity_autocomplete',
'#title' => $this->t('Author'),
'#target_type' => 'user',
'#default_value' => $items[$delta]->user ?? NULL,
];
return $element;
}
}
<?php
namespace Drupal\my_module\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
/**
* Plugin implementation of the 'author_default' formatter.
*
* @FieldFormatter(
* id="author_default",
* label=@Translation("Default"),
* field_types={
* "author"
* }
* )
*/
class AuthorFieldFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
foreach ($items as $delta => $item) {
// Render each element as markup.
$element[$delta] = ['#markup' => $item->fullname];
}
return $element;
}
}
<?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'],
],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment