Crear entidades por código en drupal 9 y 10

Para crear una entidad debemos hacerlo dentro de la estructura de carpetas src/Entity/ para nuestro ejemplo crearemos un módulo event_entity y dentro de él, una entidad que almacene información de eventos, dicha entidad se creará por medio de una clase que está en un archivo de nombre EventEntity.php, con lo que nuestra estructura quedará así:

src/Entity/EnventEntity.php

Ahora dentro de este archivo crearemos una clase crearemos un comentario que dará información a Drupal sobre nuestra entidad

<?php
namespace Drupal\event_entity\Entity;

/**
 * Defines the evententity entity.
 *
 * @ingroup event_entity
 *
 * @ContentEntityType(
 *   id = "event_entity",
 *   label = @Translation("Event Entity"),
 *   base_table = "event_entity",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "created" = "created",
 *     "changed" = "changed",
 *     "title" = "title",
 *     "subject" = "subject",
 *   },
 *   handlers = {
 *     "views_data" = "Drupal\views\EntityViewsData"
 *   }
 * )
 */

Ahora vamos a crear una la clase EventEntity que extenderá de ContentEntityBase e implementará ContentEntityInterface.

  • La clase ContentEntityBase tiene los métodos necesarios para interactuar con la base de datos.
  • Se suele implementar ContentEntityInterface para entidades similares a contenido que deben almacenarse en alguna base de datos y habilitar/deshabilitar revisiones y traducciones según se desee.
class EventEntity extends ContentEntityBase implements ContentEntityInterface {

}

Ahora debemos poner el método baseFieldDefinitions y dentro de él los campos de nuestra entidad, para nuesto ejemplo  crearemos los campos id, title, link, start_date, start_date, end_date.

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the entity.'))
      ->setReadOnly(TRUE);
      
    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t('The UUID of the event entity.'))
      ->setReadOnly(TRUE);
      
    $fields['link'] = BaseFieldDefinition::create('link')
      ->setLabel(t('Link'))
      ->setDescription(t('The link of the event entity.'))
      ->setDefaultValue('www.example.com');

    $fields['start_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Start Date'))
      ->setDescription(t('The Start Date of the event entity.'))
      ->setDefaultValue('');

    $fields['end_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('End Date'))
      ->setDescription(t('The End Date of the event entity.'))
      ->setDefaultValue('');      
      
     return $fields;      
  }      

Con lo que nuestro código quedaría así:
 

<?php
namespace Drupal\event_entity\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Defines the evententity entity.
 *
 * @ingroup event_entity
 *
 * @ContentEntityType(
 *   id = "event_entity",
 *   label = @Translation("Event Entity"),
 *   base_table = "event_entity",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *     "created" = "created",
 *     "changed" = "changed",
 *     "title" = "title",
 *     "subject" = "subject",
 *   },
 *   handlers = {
 *     "views_data" = "Drupal\views\EntityViewsData"
 *   }
 * )
 */
class EventEntity extends ContentEntityBase implements ContentEntityInterface {
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the entity.'))
      ->setReadOnly(TRUE);
      
    $fields['title'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t('The UUID of the event entity.'))
      ->setReadOnly(TRUE);
      
    $fields['link'] = BaseFieldDefinition::create('link')
      ->setLabel(t('Link'))
      ->setDescription(t('The link of the event entity.'))
      ->setDefaultValue('www.example.com');

    $fields['start_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Start Date'))
      ->setDescription(t('The Start Date of the event entity.'))
      ->setDefaultValue('');

    $fields['end_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('End Date'))
      ->setDescription(t('The End Date of the event entity.'))
      ->setDefaultValue('');      
      
     return $fields;      
  }
}


Al instalar nuestro módulo veremos la tabla event_entity con los campos que acabamos de definir.

Me pareció interesante el artículo

Deseo más información

O también puedes comunicarte con nosotros.

por whatsapp por whatsapp

Añadir nuevo comentario

Me gustaría más información sobre:

CAPTCHA