Add translation to a term or node programmatically in Drupal 8

Posted on Thursday, September 28, 2017
Add translation to a term or node programmatically in Drupal 8

 

It's easy to create a node or a term programmatically in Drupal 8. Here is the script to create term programmatically.

<?php
  $term 
Term::create([ 
    
'name' => 'Apple',
    
'vid' => 1
  ]);
  
$term->save();
?>

But a small change in this simple script will allow you to added translation for this term as well.

<?php
  $term 
Term::create([ 
    
'name' => 'Apple',
    
'vid' => 1,
  ]);
  
// Add translation.
  
$term->addTranslation('ar', ['name' => 'Apfel',]);
  
$term->save();
?>

Similarly translations can be added for node or any other entity programmatically.

 

Disqus Comments