Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Create and translate a multilingual nodes programmatically.

By editor , 28 November, 2015
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();

Tags

  • Drupal 8
  • Code
  • Translation
  • Node
  • Add new comment

Comments2

Plain text

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

Pauloscorps (not verified)

8 years 10 months ago

I get the following error :…

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).

  • Reply

Adrian (not verified)

8 years 10 months ago

In reply to I get the following error :… by Pauloscorps (not verified)

You probalby didnt defined…

You probalby didnt defined English as a language in your System.

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer