Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I'm constantly getting the 'The host entity cannot be changed.' exception, despite using the version that includes the fixes from #1316162: Support content translation and host entity cloning. I'm currently using this workaround in my custom module:
/**
* Implements hook_field_attach_presave().
*/
function glue_field_attach_presave($entity_type, $entity) {
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
$instances = field_info_instances($entity_type, $bundle);
foreach ($instances as $instance) {
$field = field_info_field($instance['field_name']);
if ($field['type'] == 'field_collection') {
if (isset($entity->{$field['field_name']})) {
_glue_fix_field_collection($entity, $entity_type, $field['field_name']);
}
}
}
}
/**
* Helper function.
*/
function _glue_fix_field_collection(&$entity, $entity_type, $field_name) {
list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
foreach ($entity->{$field_name} as $lang => $deltas) {
foreach ($deltas as $delta => $item) {
$query = new EntityFieldQuery();
$query->fieldCondition($field_name, 'value', $item['entity']->item_id, '=');
$query->entityCondition('entity_id', $id, '!=');
$query->entityCondition('entity_type', $entity_type);
$result = $query->execute();
// reset the item_id if it exists on an other entity.
if (!empty($result) || empty($id)) {
$entity->{$field_name}[$lang][$delta]['entity']->item_id = '';
$entity->{$field_name}[$lang][$delta]['entity']->is_new = TRUE;
}
}
}
Comments
Comment #2
Jelle_SComment #3
jmuzz CreditAttribution: jmuzz commented