Skip to main content

Adding EntityTypeManagerInterface as a Dependency into the Controller

This is a basic example on how to use the Dependency Injection for the EntityTypeManagerInterface.

By doing this you avoid having into your controller code like this:

    $query = \Drupal::entityQuery('node')
      ->condition('type', 'market')
      ->condition('status', 1)
      ->sort('title', 'ASC');

    $nids = $query->execute();

    if (is_array($nids) && !empty($nids)) {
      $nodes = Node::loadMultiple($nids);
      $items = $this->parseNodes($nodes);
    }

By adding the EntityTypeManagerInterface we can now remove using \Drupal into our Controller which is considered as a bad coding practice.

<?php

namespace Drupal\custom_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class BoxContainerController return the active states for selling.
 */
class BoxContainerController extends ControllerBase {

  /**
   * The entity storage manager for response_header entities.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
     );
  }

  /**
   * BoxContainerController constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {

    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * Content.
   *
   * @return array
   *   Return theme template with data for rendering
   */
  public function content() {

    $data = [
      'items' => $this->getAvailableShops(),
      'id' => 'ShopModalBoxContainerController',
    ];

    return [
      '#theme' => 'winebow_shopmodal_modal',
      '#data' => $data,
    ];
  }

  /**
   * An array of the active market states.
   *
   * @return array
   *   An array with the active states
   */
  private function getAvailableShops() {

    $items = [];
    $storage = $this->entityTypeManager->getStorage('node');
    $query = $storage->getQuery()
      ->condition('type', 'market')
      ->condition('status', 1)
      ->sort('title', 'ASC');

    $nids = $query->execute();

    if (is_array($nids) && !empty($nids)) {
      $nodes = $storage->loadMultiple($nids);
      $items = $this->parseNodes($nodes);
    }

    return $items;

  }

  /**
   * A parsed associative array of the active market states.
   *
   * Holds only title and region code data per state.
   *
   * @return array
   *   Returns active States parsed array
   */
  private function parseNodes(array $nodes) {

    $data = [];

    foreach ($nodes as $key => $node) {

      $title = trim(str_ireplace('Test ', '', $node->getTitle()));

      // Get the Administrative Area code.
      $address = $node->get('field_address')->first();
      $region_code = $address->get('administrative_area')->getValue();

      $data[$key] = [
        'title' => $title,
        'region_code' => $region_code,
      ];

    }
    return $data;
  }

}

 

custom module php controller dependency injection