John John has been developing websites and software for over 20 years. Focusing on Drupal over the last 12 years.

Drupal 8: Creating custom content entities

Drupal 8: Creating custom content entities

As you start to work on more complex applications, you will find the need to create custom entities rather than using content types.

In Drupal, similar entities are grouped into Entity Types, which have subtypes known as Bundles, to which fields can be attached.

When to use custom entities?

Nodes can be used to store any kind of data in Drupal. However, nodes implement lots of hooks that you may not require. Also, all the data is stored in a single database table. This can have an impact on performance.

So by creating your own custom entity, you have full control over menus, paths, admin UX, data storage and workflows.

If you read my previous post about using Drupal Console to create Views Field plugins, then we can also use the console to create the boilerplate code for our custom entity.

Creating custom entities using Drupal Console

drupal generate:entity:content --module="mymodule" --entity-class="CustomEntity" \
--entity-name="custom_entity" --base-path="/admin/structure" --label="Custom entity" \
--is-translatable --revisionable

By running the command above, Drupal Console will ask you some questions and then create lots of lovely boilerplate code for us.

Drupal Console Boilerplate Code

Once you have enabled your module or cleared caches if it is an existing module, you will then have two extra menu entries in the /admin/structure section called Custom entity settings and Custom entity list.

Also, your newly created entity will have full Views integration.

Custom entity settings

In this section you can add fields, manage displays just like we do with node types.

Custom entity list

This section will list all the Custom entities that you create.


So as you can see it is very straight-forward to create custom entities in Drupal 8 using the Drupal Console and it certainly gives you a head start when you need to customise your entity going forward.

Please leave a comment with any feedback or if you feel I have explained something incorrectly.

comments powered by Disqus