Drupal Console makes entity develoment a snap!

Submitted by cerium on Sat, 10/20/2018 - 20:34

Drupal Console and Custom Entities

At some point in Drupal development, you realize that you are stretching the Node and Taxonomy modules way, way farther than they should be stretched, and you start wanting to look at custom entities. Maybe its because you are trying to fit all of your data into one table, and custom entities work well for that (this is part of the key for Spectra Analytics). Or, maybe you have a very simple entity that doesn't require the overhead typically associate with the usual publisher-oriented modules. Either way, you decide custom entities are the way to go.

However, if you've had to actually write out the code in Drupal 8, you know it's a pain! There are so many files that go into making a custom entity, and doing it once and copying it to another module comes with a high probability of missing a place where you needed to change names. Fortunately, the folks behind Drupal Console have automated the entire process, such that hours of work can be done in minutes.


Drupal Console may be installed either by Composer or by downloading a PHP application, and we prefer the latter. This is our take on the installation directions from https://docs.drupalconsole.com/en/getting/launcher.html

curl https://drupalconsole.com/installer -L -o /var/local/drupal.phar
ln -s /var/local/drupal.phar /usr/local/bin/drupal
chmod +x /usr/local/bin/drupal

Here, we download the .phar to a location where we keep executables, and symlink to /usr/local/bin . In the official documentation, they also suggest copying the file directly, but either way you type "drupal [command]" and it is interpreted anywhere.


Creating Entities

Per the documentation, you have the option to create entities with a number of command line options, but if they aren't set, you will be given a dialog in which you are asked about major settings for your new custom entity. You must add to an existing module, so if you don't have one, type

drupal generate:module

from your Drupal root to make a module.

For content entities...

drupal generate:entity:content

For configuration entities...

drupal generate:entity:config

And after answering a few basic questions, most of the basics are in place! This lets you get past many of the mundane tasks of setting up basic routing and permissions, so you can dive right in to setting up custom fields and working on the custom features that really need your attention.

As we use Drupal Console ourselves, we will continue to report and give examples of the interesting features that you can build quickly with it. If you went ahead with the above install, just type "drupal" from within your Drupal directory to see what we mean - there are many useful tools in there, and we're thankful for the developers behind it!