List enabled view modes (view displays) for a bundle of an entity type
A developer needs to find which bundles of a given entity type have a specific view mode enabled – for example, to conditionally apply logic only to bundles where a teaser or custom view mode is configured.
private function getBundlesWithViewmode(string $entity_type, string $view_mode): array {
$bundles = [];
foreach (\Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type) as $bundle => $info) {
$view_modes = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle($entity_type, $bundle);
if (isset($view_modes[$view_mode])) {
$bundles[] = $bundle;
}
}
return $bundles;
}
Issue:
A developer needs to find which bundles of a given entity type have a specific view mode enabled – for example, to conditionally apply logic only to bundles where a teaser or custom view mode is configured.
Solution:
This snippet finds all bundles for a certain entity type which have a certain view mode enabled.
Example: Find all node bundles that have a teaser view display.
→ php $this->getBundlesWithViewmode('node', 'teaser'); Result: php ['article', 'blog']
Ihre Drupal-Website zukunftssicher machen
Wir prüfen Ihr System und zeigen, was Sie für AI, Wartung und Upgrades brauchen.