3

I need to create multilingual node programmatically in Drupal with entity_translation.

No problem to create the node, but I have no idea how can I create the translation ( + field translated).

I don't want to create another node, just translate it (same nid).

My language is FR , I need translation in EN and DE.

2 Answers 2

2

Found the answer ! Thanks to my co worker.

In order to add translation to a node you need to add every translatable field like this in your creation node code :

 $node->field_trailer['fr'][0]['value'] = $movie['link'];  
 $node->field_trailer['de'][0]['value'] = $movie['link'];  
 $node->field_trailer['en'][0]['value'] = $movie['link'];

And after node_save($node); add

  node->translations->data['de']['entity_type'] = 'node'; 
  $node->translations->data['de']['entity_id'] = $node->nid;
  $node->translations->data['de']['language'] = 'de'; 
  $node->translations->data['de']['source'] = 'fr';   
  $node->translations->data['de']['uid'] = $node->uid;  
  $node->translations->data['de']['status'] = $node->status; 
  $node->translations->data['de']['translate'] = 0; 
  $node->translations->data['de']['created'] = $node->created; 
  $node->translations->data['de']['changed'] = $node->changed;

For each language and the node_save($node) again.

1
  • Works fine for terms as well.
    – leymannx
    Commented Mar 4, 2016 at 21:46
2

Here is other solution. Perhaps you already have $node object (from node_load or menu_get_object etc), and $lang - langcode to translate:

$handler  = entity_translation_get_handler('node', $node);
$translations = $handler->getTranslations();
if ($lang !== $node->language && !isset($translations->data[$lang])) {
  $translation_node = $node;
  $values = array();
  // Change translatable fields languages to trasnlation language.
  foreach(field_info_instances('node', $node->type) as $instance) {
    $field_name = $instance['field_name'];
    $field = field_info_field($field_name);
    if ($field['translatable'] && isset($translation_node->$field_name)) {
      foreach ($translation_node->$field_name as $lang_key => $field) {
        if ($lang_key == $node->language) {
          $values[$field_name][$lang] = $field;
        }
      }
    }
  }
  // Create a translation.
  $translation = array(
    'translate' => 0,
    'status' => 1,
    'language' => $lang,
    'source' => $node->language,
  );
  $handler->setTranslation($translation, $values);
  node_save($translation_node);
}
2
  • Thank you, after some fine tuning it worked for me. Just one thing: how to translate title of the node?
    – Deele
    Commented Oct 20, 2014 at 22:19
  • 2
    You should use drupal.org/project/title module
    – tornado_tm
    Commented Oct 24, 2014 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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