Skip to content

10. Categorizing different entities of the same entity type

Drupal provides a mechanism to distinguish content entities of the same type and attach different behavior to the entities based on this distinction. In the case of event entities, for example, it allows events to have different behavior based on the type of event they are. The nomenclature is that entity types can have bundles where each entity of that entity type belongs to a certain bundle.

Generally a configuration entity type is used to provide the bundles for a content entity type. In this case each Event type entity will be a bundle for the Event entity type.

  • Delete the existing event(s)

    Visit /admin/content/events/manage/2/delete and press Delete.

    Adding a bundle field cannot be done when there are existing entities.

  • Add the following to the entity_keys section of the attributes in src/Entity/Event.php:

    'bundle' => 'type',
  • Add the following to the attributes in src/Entity/Event.php:

    bundle_entity_type: 'event_type',
  • Replace the add-form link in the attributes in src/Entity/Event.php with:

    '/admin/content/events/add/{event_type}'
  • Add the following to the links section of the attributes in src/Entity/Event.php with:

    'add-page' => '/admin/content/events/add',
  • Add the following to the attributes in src/Entity/EventType.php:

    bundle_of: 'event',

Like for the id and uuid fields, the field definition for the type field is automatically generated by ContentEntityBase::baseFieldDefinitions().

  • Run drush entity:updates

  • Note that the type column has been added to the {event} table.

  • Visit /admin/structure/event-types/add and add a Conference event type

  • Visit /admin/content/events/add

    Note that the event types are displayed as options.

  • Create an event