When translating a node with node level translation all entity reference fields are initially unset as the entities referenced by the source content are not available as options in the translated node form (unless they are language undefined). In keeping with other field types it would be good to pre-populate these fields with the values from the source language node. In this instance this would substituting the source values with entity ID's with their translations in the current language if available.

Below is code I have written to handle this in my own module but there could be a more elegant approach.

/*
 * Implementation of hook_interface_field_widget_form_alter
 * Update default values for entityreferences when performing a translation
 * to ensure that translations of those entities referenced on the source node
 * are set as defaults if available
 */
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) { 
  if ($context['field']['type']=='entityreference' && isset($element['#entity']->translation_source)) { //only apply to entityreference fields when creating a translation
    
    foreach($context['items'] as $sourceVals) { 
      if(!in_array($sourceVals['target_id'] ,$element['#default_value'])) { //source node not available in the field options so assume it has been filtered out by language
        
        //need to retrieve the tnid (translation set id) for the node to ensure we can match no matter
        //which was the original language of the node
        $result = db_select('node', 'n')
          ->fields('n', array('tnid', 'nid'))
          ->condition('nid', $sourceVals['target_id'])
          ->execute()
          ->fetchCol();
        $tnid = (isset($result[0])? $result[0] : 0); 
        if ($tnid) { //if tnid is 0 no translations exist
          $translations = translation_node_get_translations($tnid);
          if (isset($translations[$element['#entity']->language])) {
            $element['#default_value'][] = $translations[$element['#entity']->language]->nid;
          }
        }
      }
    }
  }
}

Comments

netsensei’s picture

Project: Translated Entity Reference » Entity reference

This module only focusses on making the query of the autocomplete listing language aware. It does not set the default values of the fields upon translation. I'm moving this to the Entity Reference issue queue.

knalstaaf’s picture

This module works fine, thanks!

In order to get it properly working I configured my Entity Reference view as such that all values are available (by eliminating some Views filters), regardless of language. Then I assigned all values as default in the Entity Reference field itself.
After that I put the filters back, and now it works as desired.