Add new comment | Drupal 8

Add new comment

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 ';
}

Plain text

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