Handlers

Last updated on
22 April 2021

While entities represent a piece of data, handlers are responsible for acting on and with them. Handlers of an entity can be accessed through the entity_type.manager service.

Different types of handler are responsible for different functionality. The handler type is identified by a string, used in the entity type annotation to set the handler class for the entity type, and when retrieving the handler:

$handler = \Drupal::entityTypeManager()->getHandler($entity_type_id, $handler_type);

Some handler types have a dedicated retrieval method on EntityTypeManager.

Some handler types, such as 'storage' and 'access' will default to a standard implementation if none is defined in the entity type. Other types of handler will simply be empty if the entity type does not define it.

Handler type string are arbitrary, and modules are free to define their own handler types.

Note: Handlers were previously known as Controllers. See Change Record.

Storage

The storage handler implements EntityStorageInterface and will default to ContentEntityStorageBase, a handler that implements standard methods for crud operations.

Example usage:

/** @var \Drupal\node\NodeStorageInterface $storage */
$storage = \Drupal::entityTypeManager()->getStorage('node');

$storage->load(1);
$storage->loadMultiple([1, 2, 3]);
// Equivalent to $node->save().
$storage->save($node);
$new_node = $storage->create(['title' => 'My awesome node']);

Access Control

The access handler implements EntityAccessControlHandlerInterface and will default to EntityAccessControlHandler.

/** @var \Drupal\Core\Entity\EntityAccessControlHandlerInterface $access_control */
$access_control = \Drupal::entityTypeManager()->getAccessControlHandler('node');

List Builder

The list builder implements EntityListBuilderInterface and will default to EntityListBuilder

View Builder

The view builder implements EntityViewBuilderInterface and will default to EntityViewBuilder

Example usage:

$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';

// Load node.
$node = \Drupal::entityTypeManager()
  ->getStorage($entity_type)
  ->load($nid);
  
// Translate, if necessary.
$lang_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
$node = $node->getTranslation($lang_code);

// Build a render array for the node.
$build = \Drupal::entityTypeManager()
  ->getViewBuilder($entity_type)
  ->view($node, $view_mode);

Form

The form handler implements EntityFormInterface. Since EntityForm already implements that interface, you can extend it to provide classes for such high level operations as add, edit, and delete. You would then provide user access to those operations through routing.yml files. See the Drupal Examples project configuration entity example, src/Entity/Robot.php.

Help improve this page

Page status: No known problems

You can: