Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
* Temporary function to delete fields attached to entities that have already
* been deleted. This assumes there are no deleted fields that need to be
* purged as this won't actually remove their tables in the database. Use with
* caution and only when fully understanding what this does compared to
* field_purge_batch and field_purge_field_storage.
function _fix_missing_entities_during_field_purge() {
/** @var \Drupal\Core\Field\DeletedFieldsRepositoryInterface $deleted_fields_repository */
$deleted_fields_repository = \Drupal::service('entity_field.deleted_fields_repository');
$info = \Drupal::entityManager()->getDefinitions();
$definitions = $deleted_fields_repository->getFieldDefinitions();
foreach ($definitions as $definition) {
$entity_type = $definition->getTargetEntityTypeId();
if (!isset($info[$entity_type])) {
echo $entity_type . ' ' . $definition->getName() . "\n";
// Retrieve all deleted field storages. Any that have no fields can be purged.
foreach ($deleted_fields_repository->getFieldStorageDefinitions() as $field_storage) {
if (!isset($info[$field_storage->getTargetEntityTypeId()])) {
echo $field_storage->getTargetEntityTypeId() . ' ' . $field_storage->getName() . "\n";
$fields = $deleted_fields_repository->getFieldDefinitions($field_storage->getUniqueStorageIdentifier());
if (empty($fields)) {
// Invoke external hooks after the cache is cleared for API consistency.
\Drupal::moduleHandler()->invokeAll('field_purge_field_storage', [$field_storage]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment