EntityTypeManager en Drupal

Entity Type Manager
Solucionex
10
Nov 23

El EntityTypeManager facilita el acceso a los diferentes tipos de entidades que se pueden encontrar en Drupal  (View, node, term, file...) sin necesidad de loads estáticos. Con entityTypeManager se consigue limpiar el código y se evita la sobrecarga de las diferentes entidades.

El acceso al EntityTypeManager se puede realizar mediante inyección de dependencias o llamando directamente a la clase Drupal.

Inyección de dependencias

<?php
declare(strict_types = 1);
namespace Drupal\[THEME];
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomClass implements ContainerInjectionInterface {
  /**
   * Class constructor.
   */
  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
  ) {}
  /**
   * {@inheritdoc}
   */
   public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
    );
  }
  
  protected function customFunction() {
    /** @var \Drupal\views\ViewEntityInterface|null $view */
    $view = $this->entityTypeManager->getStorage('view')->load('[VIEW_ID]');
    $node = $this->entityTypeManager->getStorage('node')->load('[NODE_ID]');
    $files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['filename' => '[FILE_NAME]']);
   
    $term = $this->entityTypeManager->getStorage('taxonomy_term')->load([TAXONOMY_ID]);
  }
}

Llamando a la clase de Drupal 

<?php

/**
 * @file
 * Functions to support theming content layout in the Wingsuit theme.
 */

declare(strict_types = 1);

use Drupal\[THEME]\PageTitlePreprocess;

/**
 * Implements theme_preprocess_page_title().
 *
 * Page title customizations in specific pages.
 */
function THEME_preprocess_page_title(array &$variables): void {
  $view = \Drupal::entityTypeManager()->getStorage('view')->load('[VIEW_ID]');
  $node = \Drupal::entityTypeManager()->getStorage('node')->load('[NODE_ID]');
  $files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['filename' => '[FILE_NAME]']);
  $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load([TAXONOMY_ID]);
}

Conseguir el tipo de entidad

Para poder acceder al tipo de entidad se se puede hacer con las siguientes funciones:

// Get the entity type or the entity type ID.
$entity->getEntityType();
$entity->getEntityTypeId();

$needed_type = 'node';
if ($entity->getEntityTypeId() == $needed_type) {
// TODO
}

Crear un Entity Object

Con el entityTypeManager se pueden generar nuevas entidades especificando el tipo de nodo.

\Drupal::entityTypeManager()->getStorage('node')->create(['type' => '[NODE_TYPE]', 'title' => '[NODE_TITLE]']);

Eliminar diferentes entidades

De la misma manera que se pueden crear nuevos entity Objects se pueden eliminar.

\Drupal::entityTypeManager()->getStorage([ENTITY_TYPE])->delete([ENTITY_IDS]);

Diferentes maneras de cargar las entidades

También se pueden cargar las entidades de diferentes formas.

// Cargar multiples entidades por ID.
\Drupal::entityTypeManager()->getStorage([ENTITY_TYPE])->loadMultiple([1, 2, 3]);

// Cargar entidades por propiedades. Ejemplo con un nodo.
\Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'page']);

Para más información podéis acceder al siguiente enlace de la documentación de Drupal.

Drupal
EntityTypeManager