1

I use entity_translation and have an en node currently without translations. Assume it has fields field_foo and field_bar so currently they are:

$node->field_foo['en'][0]['value'] = 'foo';
$node->field_bar['en'][0]['value'] = 'bar';

I want to programmatically add anfr translation but only translate field_foo so I do:

$node->field_foo['fr'][0]['value'] = 'foo FR';

entity_translation_get_handler('node', $node)->setTranslation(array(
  'translate' => 0,
  'language' => 'fr',
  'source' => 'en'
), $node);
field_attach_update('node', $node);

This works but now if I edit (or devel) the fr node, field_bar is empty. On the frontend it does show "bar" which is the en value, but I've noticed that if I create the translation via the Drupal UI then the field_bar is not empty and contains a copy of the en value.

So, does anyone know of a way that the API will copy all values upon translation creation? Or should I be doing that myself manually via the code?

2
  • Hi, did you manage with issue? – makbuk Nov 5 '17 at 22:12
  • @makbuk I used custom code. I've added it as an answer. – cherouvim Nov 6 '17 at 9:41
1

I ended up doing it manually via code:

function _populate_translation_values($node, $targetLanguage) {
  $fields = field_info_instances('node', $node->type);
  foreach($fields as $fieldName=>$fieldInstance) {
    $fieldInfo = field_info_field($fieldName);

    // only process translatable fields
    if (!$fieldInfo['translatable']) continue;

    // ignore fields which are complicated to copy - could be fixed in the future
    if (in_array($fieldInfo['type'], array('field_collection'))) continue;

    // skip fields which already have a value in the target language
    if (isset($node->{$fieldName}[$targetLanguage])) continue;

    // skip fields which don't have a value in the source language
    if (!isset($node->{$fieldName}[$node->language])) continue;

    // copy value
    $node->{$fieldName}[$targetLanguage] = $node->{$fieldName}[$node->language];
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.