Change record status: 
Project: 
Introduced in branch: 
3.x
Introduced in version: 
3.0.0-beta1
Description: 

In version 2, custom elements for entities had "type" and "view-mode" attributes output by default (added by CustomElementsGenerator::getEntityDefaults()), though the "view-mode" attribute was only output in HTML format, and suppressed in JSON format.

In version 3, these are not output by default.

Customizing defaults

To add these attributes back to output:

  • Either add them explicitly as fields in a custom elements display,
  • Or, when having Layout Builder enabled or you want to keep your custom processor code (i.e. in version 3, your custom elements displays have "Automatic processing" enabled): Add them back in an alter hook:
    function MYMODULE_custom_element_entity_alter(CustomElement $custom_element, ContentEntityInterface $entity, string $viewMode) {
      if (!$custom_element->getAttribute('type')) {
        $custom_element->setAttribute('type', $entity->bundle());
      }
      // This was likely not present in JSON output / is only necessary for HTML:
      if (!$custom_element->getAttribute('view-mode')) {
        $element->setAttribute('view-mode', $viewMode);
      }
    }
    

If most of your entities are built through the standard processor code in version 2 (DefaultContentEntityProcessor), there's another way instead of the alter hook above (though its advantages over the alter hook ar unclear):

  • Make sure a custom elements display exists with name == the entity type, and "Automatic processing" enabled, for all relevant entities/bundles.
  • Add the following class to your module:
    namespace Drupal\MY_MODULE\Processor;
    
    use Drupal\custom_elements\CustomElement;
    use Drupal\custom_elements\Processor\DefaultContentEntityProcessor;
    
    class V2DefaultContentEntityProcessor extends DefaultContentEntityProcessor {
    
      public function addtoElement($data, CustomElement $element, $viewMode, $key = '') {
        // Add attributes that were standard in custom_elements v2.
        if ($data->bundle() != $data->getEntityTypeId()) {
          $element->setAttribute('type', $data->bundle());
        }
        // This was likely not present in JSON output / is only necessary for HTML:
        $element->setAttribute('view-mode', $viewMode);
        parent::addtoElement($data, $element, $viewMode, $key);
      }
    
    }
    
  • Add in your services.yml file:
    services:
      # Override custom_elements default, priority + 1
      MY_MODULE.processor.default_content_entity:
        class: Drupal\MY_MODULE\Processor\V2DefaultContentEntityProcessor
        tags:
          - { name: custom_elements_processor, priority: -99 }
    
Impacts: 
Module developers