You are here

function lingotek_update_entity_references in Lingotek Translation 7.7

Update incorrect entity references

1 string reference to 'lingotek_update_entity_references'
lingotek_get_entity_reference_updater_batch_elements in ./lingotek.batch.inc
Get entity reference updater operations (Re-connect translation parents to translation children)

File

./lingotek.util.inc, line 1350
Utility functions.

Code

function lingotek_update_entity_references($entity, &$context) {
  $entity_changed = FALSE;
  $field_definitions = field_info_fields($entity->type);
  $host_language = $entity->language;
  $parent_node = node_load($entity->nid);
  foreach ($field_definitions as $definition) {
    if ($definition['type'] === 'entityreference') {
      $field_name = $definition['field_name'];
      $entity_reference_target_type = $definition['settings']['target_type'];
      if ($entity_reference_target_type !== 'node') {
        continue;
      }
      if (isset($parent_node->{$field_name}['und'])) {
        $lang_key = 'und';
        $child_node_ids = $parent_node->{$field_name}['und'];
      }
      elseif (isset($parent_node->{$field_name}[$host_language])) {
        $lang_key = $host_language;
        $child_node_ids = $parent_node->{$field_name}[$host_language];
      }
      for ($x = 0; $x < count($child_node_ids); $x++) {
        $child_node_id = $child_node_ids[$x]['target_id'];
        $child_entity = node_load($child_node_id);
        $child_language = $child_entity->language;
        if ($host_language !== $child_language) {
          $child_tnid = $child_entity->tnid;
          $translated_nid = db_select('node', 'n')
            ->fields('n', array(
            'nid',
          ))
            ->condition('tnid', $child_tnid)
            ->condition('language', $host_language)
            ->execute()
            ->fetchField();
          if ($translated_nid) {
            $entity_changed = TRUE;
            $parent_node->{$field_name}[$lang_key][$x]['target_id'] = $translated_nid;
          }
        }
      }
    }
  }
  if ($entity_changed) {
    entity_save('node', $parent_node);
    if (empty($context['results'])) {
      $context['results']['entity_reference_fixed'] = 1;
    }
    else {
      $context['results']['entity_reference_fixed'] += 1;
    }
  }
  else {
    if (empty($context['results'])) {
      $context['results']['entity_reference_not_fixed'] = 1;
    }
    else {
      $context['results']['entity_reference_not_fixed'] += 1;
    }
  }
}