Drupal - How to add a view mode for entity type?

View modes are configuration entities.

Like anything else that is a config entity, it's very simply to put into "code": Make it default configuration. Create it in the UI, do a configuration export (admin/config/development/configuration/single/export), and then place core.entity_view_mode.$entity_type.$view_mode.yml file into config/install inside your module.

The view mode will then automatically be imported and created when the module is installed.

Note that it's not hardcoded then, so a user could remove it. If you want to prevent that, you can implement hook_entity_view_mode_access() to deny delete access to your entity for everyone.

By default, you will have a problem re-installing the module because it will not remove that view mode when you uninstall the module and display an error when you install it again. There are two ways to fix that:

  • Move the config to config/optional instead of config/install. Then it will only be created if it doesn't exist yet.
  • Add an enforced dependency on your module, which will ensure that it will be removed when the module is uninstalled. Note that this only works if you had this in place when you installed the module the first time.

Like this:

  dependencies:
    enforced:
      module:
        - yourmodule

To create a View mode in Drupal 8 (i.e. a custom manage display), this can now be accomplished through the UI:

admin/structure/display-modes/view

Or if you'd like to programatically provide a View mode with your module, follow these steps:

  1. Create a custom module
  2. Create a config/install directory within your module
  3. Inside of config/install, create a file called core.entity_view_mode.node.my_module.yml

Then inside of core.entity_view_mode.node.my_module.yml add this:

langcode: en
status: true
dependencies:
  module:
    - node
    - my_module
id: node.my_module
label: 'My Module'
targetEntityType: node
cache: true

Then install your module (you'll have to uninstall and then re-install your module if it is already installed). You'll now have a custom view mode that can be enabled for all of your content types.

To support other types of entities (e.g. comment, user) just create a new .yml file and replace occurrences of node with your desired entity type.

Tags:

Entities

Views

8