Create and translate a multilingual nodes programmatically.

Submitted by editor on Sat, 11/28/2015 - 19:10

How to create and translate a multilingual nodes programmatically ?

Programmatically create and translate nodes.

use Drupal\node\Entity\Node;
$node = Node::create([
  // The node entity bundle.
  'type' => 'article',
  'langcode' => 'en',
  'created' => REQUEST_TIME,
  'changed' => REQUEST_TIME,
  // The user ID.
  'uid' => 1,
  'title' => 'My test!',
  // An array with taxonomy terms.
  'field_tags' =>[2],
  'body' => [
    'summary' => '',
    'value' => '<p>The body of my node.</p>',
    'format' => 'full_html',
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/my/path", "en");
$node_es = $node->addTranslation('es');
$node_es->title = 'Mi prueba!';
$node_es->body->value = '<p>El cuerpo de mi nodo.</p>';
$node_es->body->format = 'full_html';
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/mi/ruta", "es");

Note : This example has not checked bu my self.
Example from


Example 2 :  (Tested)

//use Drupal\node\Entity\Node;
//Create Entity
$entity = \Drupal\node\Entity\Node::create([
  'type' => 'article',
  'title' => "Test Title English"
//Add French translation
$entity->addTranslation('fr', ['title' => "Title in French"])->save();

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.