How to create a custom content entity type in Drupal 8

Leveraging the power of Drupal console

This blog post assumes you have already installed Drupal console. The installation instructions can be found on the official Drupal console website.

Check your version and update if needed

At the time of writing the latest version of Drupal console is 1.0.0-beta3. Make sure to call the Drupal console commands from your website root.

You can check your Drupal console version and how to update it when you call:

Drupal console
When calling drupal you can see your current version of Drupal console, if you want to update to the latest version you call drupal self-update

List of available commands

drupal list
Drupal console commands
Extensive list of all available commands in Drupal console (not all commands are on this screenshot)

Generating a new module with Drupal console

With the following command you can generate the boilerplate code for a new module:

drupal generate:module
Generate a new module with Drupal Console
Wizard to generate a new custom module with Drupal console

Generating a custom content entity with Drupal console

You can create a custom content entity with the following command:

drupal generate:entity:content
Generate a custom content entity with Drupal Console
Wizard to generate a custom content entity with Drupal console

Adding fields to your custom content entity

Before enabling your module you should add all the fields programmatically. 

In our custom module named fonzerello you can now edit the /src/Entity/MyKickAssEntity.php file. 

In this example I add a test field in the following function baseFieldDefinitions()

    // A title field.
    $fields['test'] = BaseFieldDefinition::create('string')
      ->setDescription(t('A test field!'))
        'max_length' => 255,
        'text_processing' => 0,
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -4,
      ->setDisplayOptions('form', array(
        'type' => 'string_textfield',
        'weight' => -4,
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

Now enable your module and see your custom content entity in action.

Custom content entity
The custom content entity with our added field named Test

Now it's time to pat yourself on the shoulder, you just created your first custom content entity with Drupal console.


Meer leesvoer

I have been working on a Drupal 8 multisite and at some point I had to set up a new site in the structure. The...
In this blog post you will learn how to add a theme field preprocess function in your theme.
In this blog post I show you how to login and logout from a Drupal 8 Back-end from an Ionic app
It's quite easy to create a node with REST in Drupal 8, in this blog post I'll show you how to do it.