Drupal Error: Mismatched Entity
I see this error about “mismatched entity” in an admin status report screen frequently enough that I need to jot it down for future reference.
The most recent one was for the “Computed Field” module (after upgrading several modules for D10 compatibility). I assume there was a change in the latest version of the module.
The specific error message was “Mismatched entity and/or field definitions… The Computed Field entity type needs to be installed.”
Getting the entity name from Drush REPL (drush php
):
> \Drupal::entityDefinitionUpdateManager()->getChangeList();
= [
"computed_field" => [
"entity_type" => 1,
],
]
I found a discussion about the deprecated drush command as well as a helper module. However, the answer I wanted was on d.o. Here is the resulting update hook:
<?php
/**
* Fix mismatched entity error for Computed Field.
*/
function mymodule_update_9501() {
$entity_name = "computed_field";
$changeList = \Drupal::entityDefinitionUpdateManager()->getChangeList();
if (!array_key_exists($entity_name, $changeList)) {
return "Skipped. The new config entity type $entity_name is already installed.";
}
try {
$EntityTypeDefinition = \Drupal::service('entity_type.manager')->getDefinition($entity_name);
\Drupal::entityDefinitionUpdateManager()->installEntityType($EntityTypeDefinition);
}
catch (\Exception $exception) {
throw new UpdateException($exception->getMessage());
}
}