- Create a MessageStorage class in the module's src directory. This class will extend the default \Drupal\Core\Entity\Sql\SqlContentEntityStorage class:
<?php
namespace Drupal\mymodule;
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
/**
* Defines the entity storage for messages.
*/
class MessageStorage extends SqlContentEntityStorage {
}
By extending the default storage class for our entity type, we can simply add new methods that are relevant to our requirements rather than implementing the extra business logic.
- Create a loadMultipleByType method; using this method, we will provide a simple way to load all messages of a specific bundle:
/**
* Load multiple messages by bundle type.
*
* @param string $message_type
* The message type.
*
* @return array|\Drupal\Core\Entity\EntityInterface[]
* An array of loaded message entities.
*/
public function loadMultipleByType($message_type) {
return $this->loadByProperties([
'type' => $message_type,
]);
}
We pass the type property so that we can query it based on the message bundle and return all matching message entities.
- Update the entity's annotation block to have the new storage handler defined:
handlers = {
"list_builder" = "Drupal\mymodule\MessageListBuilder",
"access" = "\Drupal\entity\EntityAccessControlHandler",
"permission_provider" = "\Drupal\entity\EntityPermissionProvider",
"storage" = "Drupal\mymodule\MessageStorage",
"form" = {
"default" = "Drupal\Core\Entity\EntityForm",
"add" = "Drupal\Core\Entity\EntityForm",
"edit" = "Drupal\Core\Entity\EntityForm",
"delete" = "Drupal\Core\Entity\EntityDeleteForm"
},
"route_provider" = {
"html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",
},
},
- You can now programmatically interact with your message entities using the following code:
// Get the entity type manager from the container.
\Drupal::entityTypeManager()
// Access the storage handler.
->getStorage('message')
// Invoke the new method on custom storage class.
->loadMultipleByType('message');