Friday, 15 August 2025

To use entityQuery via the service container in Drupal 10—rather than the global

 We should inject entity type manager service into class rather than Global \Drupal::entityQuery('').

It is recommended approach for better testability and adherence to Drupal’s dependency injection practices.

This is the way how we use entityQuery.

$query = \Drupal::entityQuery('node')

      ->condition('status', 0)

      ->condition('type', 'content_type')

      ->accessCheck(TRUE);

$nids = $query->execute();

Inject entity_type.manager Service

In your class (e.g., a custom block or controller), define a constructor and use the create() method to inject the service:

use Drupal\Core\Entity\EntityTypeManagerInterface;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

use Symfony\Component\DependencyInjection\ContainerInterface;

class MyCustomBlock extends BlockBase implements ContainerFactoryPluginInterface {

  protected $entityTypeManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {

    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->entityTypeManager = $entity_type_manager;

  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {

    return new static(

      $configuration,

      $plugin_id,

      $plugin_definition,

      $container->get('entity_type.manager')

    );

  }

Use getStorage() and getQuery()

public function build() { 

 $query = $this->entityTypeManager ->getStorage('node') 

 ->getQuery() 

 ->condition('type', 'article') 

 ->condition('status', 1) 

 ->accessCheck(TRUE) ->range(0, 5); 

 $nids = $query->execute(); // Load full node entities 

$nodes = $this->entityTypeManager ->getStorage('node') ->loadMultiple($nids);


\Drupal::entityQuery() : It is quick and easy but - Tightly coupled, harder to test.

Service injection : Decoupled, testable, modern and Slightly more verbose.

Use service container aligns with Drupal’s best practices for maintainable and testable code.






No comments:

Post a Comment