Direkt zum Inhalt

Devbits

Kleine Code-Schnipsel aus unserem Alltag mit Drupal, PHP und DevOps: Problem, Lösung, Code.

08.10.2026 | Pascal Crott

Get default langcode from entity

You want to find the source language of an entity programmatically (e.g. its default language).

// Assume $entity is your translatable entity object.
$default_language_entity = $entity->getUntranslated();
$default_language_code = $default_language_entity->language()->getId();

Issue:

You want to find the source language of an entity programmatically (e.g. its default language).

Solution:

Use the snippet provided. The entity will be loaded "untranslated", then its default language will be loaded.

10.09.2026 | Mathias Grab

Get "key" from entity type

When working with entities dynamically, the base field name of a specific entity key (e.g., the primary ID field) is not always known beforehand. Given only the entity type ID, the entity key needs to be determined dynamically.

$entity_type_id = 'node';
$definition = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
$id_key = $definition->getKey('id');

Issue:

When working with entities dynamically, the base field name of a specific entity key (e.g., the primary ID field) is not always known beforehand. Given only the entity type ID, the entity key needs to be determined dynamically.

Solution:

Load all base field definitions of the given entity type via entityTypeManager() and return the ID with the method getKey().

11.06.2026 | Nikolas Kopp

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']

07.05.2026 | Peter Gerken

Run missing entity Schema updates

When you see the "Entity type needs to be updated" message on the Drupal status page, usually it's not possible to solve it without custom code.

⚠️ WARNING: Potential data loss. Use with caution.

/**
 * Run missing database schema updates.
 */
function mymodule_update_10001(&$sandbox) {
  $entity_type_manager = \Drupal::entityTypeManager();
  $entity_type_manager->clearCachedDefinitions();
  $change_summary = \Drupal::service('entity.definition_update_manager')->getChangeSummary();
  foreach ($change_summary as $entity_type_id => $change_list) {
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    \Drupal::entityDefinitionUpdateManager()->installEntityType($entity_type);
  }
}

Issue:

When you see the "Entity type needs to be updated" message on the Drupal status page, usually it's not possible to solve it without custom code.

Solution:

Use this update hook in your custom module to force entity definition updates on next deployment.

Conclusion:

This is basically "drush entup", which was removed because it lead to data deletion in certain instances.

Beware:

Only use with caution and verify if this really yields the result you wanted - especially test for potential data loss.

Docs for the service if you want to know more can be found on drupal.org.

12.02.2026 | Michael Ebert

Get value of an entity field

You often need to access a value of a field within a Drupal entity programmatically, but you may encounter challenges in doing so due to the complexity of Drupal's data structure.

// For single value fields.
$entity->field_name->value;

// If you don`t know the main property.
$main_property_name = $entity->field_name->getMainPropertyName();

// For multiple value fields.
$entity->field_name->getValue();

Issue:

You often need to access a value of a field within a Drupal entity programmatically, but you may encounter challenges in doing so due to the complexity of Drupal's data structure.

Solution:

$entity->field_myfield->value

  • Direct Access: This approach directly accesses the value property of the field item.
  • Single Value: This is typically used when you are certain that the field holds a single value (e.g., a single text value, a single number, etc.). This is common with fields that are configured to store only one value.
  • Simplicity: It provides a simple and straightforward way to get the value if the field only holds one item.
  • Assumptions: It assumes that the field item exists and that the value property is the correct way to access the field data.

$entity->field_myfield->getMainPropertyName()

  • Main Property of the Field: getMainPropertyName() returns the main property of a field. For most fields, this is the value property, but it can also be another property depending on the field type. For example, for a reference field, the main property might be target_id.
  • Field Data Model: Each field in Drupal has a data model that can contains various properties. The main property is considered the primary piece of information for the field.
  • Usage in Entities: This method is useful when you want to use the field in a general context without knowing exactly which specific property represents the main information.

$entity->field_myfield->getValue()

  • Method Access: This approach uses the getValue() method to retrieve the field's value.
  • Array of Values: getValue() returns an array of all the field values. This is useful for fields that can hold multiple values (e.g., multiple text values, multiple references, etc.).
  • Structured Data: The returned array provides more structure and includes potentially other properties of the field items, not just the value property. For example, an image field might return an array with target_id, alt, title, etc.
  • Flexibility: This method is more flexible and can be used for both single and multi-value fields. You will need to handle the array appropriately in your code.

Conclusion:

  • Use $entity->field_myfield->value if you are dealing with a single-value field and want a straightforward, direct access to the field value.
  • Use $entity->field_myfield->getMainPropertyName() if you want to determine the main property of the field in a general way without knowing the specific field type.
  • Use $entity->field_myfield->getValue() if you need to handle multiple values or require the complete array structure of the field data, providing more flexibility and additional information.

29.01.2026 | Marc Hitscherich

Increasing the length of a basefield with data

You cannot change the specification of an existing field if it already has content. The reason for this is that the content itself may need to be changed as well.

<?php

/**
 * Change my_basefield max_length to 255.
 */
function my_module_update_10001() {
  $entity_type_id = 'my_entity';
  $field_name = 'my_basefield';
  $field_length = 255;

  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $schema_repository */
  $schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  /** @var \Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
  $entity_field_manager = \Drupal::service('entity_field.manager');
  /** @var Drupal\Core\Field\BaseFieldDefinition[] $base_field_definitions */
  $base_field_definitions = $entity_field_manager->getBaseFieldDefinitions($entity_type_id);
  $schema_repository->setLastInstalledFieldStorageDefinition($base_field_definitions[$field_name]);
  $field_storage_definitions = $schema_repository->getLastInstalledFieldStorageDefinitions($entity_type_id);

  // Update the serialized schema property.
  $rc = new \ReflectionClass($field_storage_definitions[$field_name]);
  $schema_property = $rc->getProperty('schema');
  $schema_property->setAccessible(TRUE);
  $schema = $field_storage_definitions[$field_name]->getSchema();
  $schema['columns']['value']['length'] = $field_length;
  $schema_property->setValue($field_storage_definitions[$field_name], $schema);

  // Update the field definition in the last installed schema repository.
  $schema_repository->setLastInstalledFieldStorageDefinitions($entity_type_id, $field_storage_definitions);

  // Update the storage schema.
  $key_value = \Drupal::keyValue('entity.storage_schema.sql');
  $key_name = $entity_type_id . '.field_schema_data.' . $field_name;
  $storage_schema = $key_value->get($key_name);
  // Update all tables where the field is present.
  foreach ($storage_schema as &$table_schema) {
    $table_schema['fields'][$field_name]['length'] = $field_length;
  }
  $key_value->set($key_name, $storage_schema);

  // Update the database tables where the field is part of.
  $db = Drupal::database();
  foreach ($storage_schema as $table_name => $table_schema) {
    $db->schema()->changeField($table_name, $field_name, $field_name, $table_schema['fields'][$field_name]);
  }

}

Issue:

You cannot change the specification of an existing field if it already has content. The reason for this is that the content itself may need to be changed as well.

Solution:

In case you just want to increase the size of a varchar field, here is an example of an update hook. Don't forget to also update the max_length in the baseFieldDefinitions method of your Entity class.