Custom Entities with Drupal Console

By shane
Fri, 2019-08-30 09:37
comments
Daily Dose of Drupal Episode #226

Share with Others

In the last episode we covered creating a Drupal 8 module with Drupal Console. In the episode before that, we covered using the Drupal 8 ECK module to create custom entities. In this episode, we cover how you can use Drupal Console to scaffold out custom entities on your Drupal 8 website. Sometimes it’s better to custom create a simple entity for a specific purpose. By creating an entity in your module rather than through the UI you are already in the code if you have a more custom use case than just a simple entity.

While you won’t find yourself needing to create a custom entity that often, using Drupal console makes it incredibly easy.

The first step is to install Drupal Console. You may have already watched the last episode that covers this, however, if not, you can install with composer using:

composer require drupal/console

This will install Drupal console in your project in the ./vendor/bin/ directory. This means you can run Drupal console using:

./vendor/bin/drupal [command]

Note, in my examples I am using Lando for my local development environment. I have it set up to allow me to run Drupal console commands on my site by running lando drupal. You can decide to install Drupal Console globally and add it to your path. Depending on the development environment your setup might be slightly different.

You can get a list of all the Drupal console commands by running Drupal Console command with no command argument:

drupal

To generate a boilerplate module with Drupal console run:

drupal generate:module

Fill out the questions asked by Drupal console. Make sure to enter a module name and description. In this example, I added a package name, didn’t include a composer.json file, and didn’t include a themable template:

Drupal Console Generate Module

At the end of the questions Drupal console will ask you if it should proceed with creating the module for you. Hit enter to default this to yes.

Drupal Console Generate Module

The next step is to create our custom entity. We want our entity to be a content entity, not a config entity. This can be accomplished with the following Drupal console command:

drupal generate:entity:content

Make sure to select the module you just created. In this case, I will call the entity Statistic and accept everything else at its defaults.

Drupal Console Generate Entity

When you get through all the questions, you will see all the files that were created:

Drupal Console Generate Entity

Now before you go turn this module on, we are going to take a quick look at the code. At the time of this guide, there is a bug that will cause you some headaches if you don’t fix it prior to enabling the module!

Take a look through all the files generated to create the entity. Don’t worry if you are a bit confused at this point, there are a lot of files and a lot of things going on here!

Open up the Statistic.php file (located in the src/Entity folder). If you called your entity something else, it will be the name of the Entity class.

At the top of the file you might notice that the line of code importing EditorialContentEntityBase is missing a semicolon. This is a bug in the code generation tool, make sure to add a semicolon there!

Fix Content Entity Error

This file is doing a lot, but the core of what it is doing is create the structure for your entity. This structure will be created in the database when you install the module. Go ahead and install the module to see how it works. You will notice that once you install the module you are given some menu options under the Admin > Structure menu.

The Statistics setting page is a placeholder where you could eventually add additional configuration settings. This file is controlled by the src/Entity/StatisticSettingsForm.php file.

You will notice you can manage field and display field just like you can with a content type. At this point, we could be done and just use the UI to configure the entity from here. However, in this case we want to add one more field to our entity before we call it finished.

Uninstall the module and open back up the Statistic.php file. Go down to the baseFieldDefinitions method and add the following code after the $field[‘name’] variable is set.

$fields['value'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Value'))
  ->setDescription(t('The value of the Statistics entity.'))
  ->setRevisionable(TRUE)
  ->setSettings([
    'max_length' => 50,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => -4,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(TRUE);

What this will do is add a new field called value. In this case we are making it a string field and the form will be displayed as a textfield. We could have made this an integer field or a decimal field, but for simplicity we will just make it a string.

If you re-install the module, you will now notice your value field is available. Go ahead and create some Statistics now!

There is a lot more you can do with it. You could spend an hour looking through all the code that was generated as there is a lot to learn! This is a good stopping point for now, as we were able to quickly create our own custom entity using Drupal console!