#! code: Drupal 9: Creating A Minimal Content Entity

Drupal CMS

I have recently been looking at generating custom content entities and this lead to generating a minimal entity that would be useful on a Drupal site.

If you’ve ever used Drupal Console to generate a content entity, then you’ll know what it generates a lot of files. There’s all sorts of classes and configuration files generated that handle everything from generating lists of entities and forms for creating new entities.

This got me thinking about what are the minimal about of configuration to generate a usable content entity. This might be used to store some simple data or to attach to other entities through an entity reference. As it happens, setting up a minimal content entity takes just a single file.

First, we need to set up an interface so that we can identify the content entity within the system. The entity is called MinimalContentEntityInterface and is located in the file src/Entity/MinimalContentEntityInterface.php within a custom module (called mymodule in this case).

<?php namespace DrupalmymoduleEntity;

use DrupalCoreEntityContentEntityInterface;

interface MinimalContentEntityInterface extends ContentEntityInterface {

}

This interface extends the ContentEntityInterface interface, which is the common interface used by all content entities in Drupal.

Next, we need to add the entity class. This is called MinimalContentEntity and is located in the file at src/Entity/MinimalContentEntity.php in the same custom module.

What we need to do in this class is add an annotation that informs Drupal of the presence of the entity. This sets the table name used to store the entity data and the entity keys we need.

We also need to create a static method called baseFieldDefinitions(), which returns the field definitions we require to create the entity.

Read more.