Drupal 9 creating custom entities

As a developer you get these requests to create projects in a framework so they can see if you fit their development team. I was asked, not so long ago, to create a headless CMS using Drupal 9, which meant creating a custom content entity type and use it via the Drupal JSON API module.

Since I haven’t touched Drupal in so many years, I had to read the Drupal docs to try understand how these modules work now and how to create them. It was a big nuisance, because their docs didn’t have a flow I could follow and their support forums have countless questions from other users with no real answers. So it was a dead end and made me question the usage of Drupal… But that’s a different story.

Finally I found some real help using their Drush CLI.

In this guide, I am using:
- macOS Big Sur 11.2.3
- PHP 7.4 (PHP 7.3 and up is required for Drupal 9)
- PHPStorm IDE
- Lando
- Composer

Get Drupal

You can get Drupal here https://www.drupal.org/download
Or get it using the DrupalComposer project:

Note: The downloaded version from drupal.org might not come with drush as a dependency so just add it in

Lando init & start

Since I’m using Lando to containerise my projects, I’ll need to start it up. Obviously you can use your own tool such as MAMP, Laravel valet etc. So you can skip this part.

Initialise a Lando project:

These are the options I chose using the Lando CLI

Start the Lando Project:

Lando Project started up

Drupal installation

Run through the Drupal CMS installation in the browser

Drupal installation in browser

Note: If you are using Lando, you can get your database info with this command

Create a custom Drupal entity type with drush

You can do a lot with the drush cli, so run lando drush help to see all the commands or go to https://www.drush.org/latest/commands/all/

Let’s create our entity type:

Enable the content entity

Enable the module in the browser with the Drupal admin backend i.e. Manage > Extend or run:

Where something_new is your custom entity module machine name.

Now you can start creating content for your entity and use it with the JSON:API or across the Drupal CMS.

Fullstack Web Developer, that loves code, design and coffee //Peace

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store