Create and translate a multilingual nodes programmatically. | Drupal 8

Create and translate a multilingual nodes programmatically.

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

How to create and translate a multilingual nodes programmatically ?

Programmatically create and translate nodes.

Example:
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',
  ],
]);
$node->save();
\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';
$node_es->save();
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), "/mi/ruta", "es");

Note : This example has not checked bu my self.
Example from https://gist.github.com/facine/35bb291811c146b6fc9e

 

Example 2 :  (Tested)

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

Comments

Pauloscorps (not verified)

Tue, 01/16/2018 - 11:52

I get the following error : InvalidArgumentException : Invalid translation language (en) specified. dans Drupal\Core\Entity\ContentEntityBase->addTranslation() (ligne 863 de /var/www/drupalvm/drupal/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Tom Bisciglia (not verified)

Fri, 02/08/2019 - 18:50

Greetings! I was racking my brain over this problem in Drupal 8. Here's how I finally got it done, This code copies title, body, all fields, and the pathauto setting. I'm sure there's room for improvement here as some meta fields probably need to get processed too. But this should get you started!

// This assumes you have a $node variable that contains the node translation you're starting with
$node_trans = $node->addTranslation('en-au'); // sample using Australian English
$node_trans->setTitle($node->getTitle());
$node_trans_fields = $node->getTranslatableFields();
foreach ($node_trans_fields as $name => $field) {
if (substr($name, 0, 6) == 'field_' || in_array($name, ['body', 'path'])) {
$node_trans->set($name, $field->getValue());
}
}
try {
$node->save();
}
catch (\Exception $error) {
$add_status .= 'ERROR saving ';
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.