How to translate an entity programmatically

Created on 5 July 2019, over 5 years ago
Updated 8 August 2023, over 1 year ago

Hi, I need help with the following: I have two languages: en and fr.
I have a node with fields that are translatable, including an image field, for which the target_id is untranslatable, but alt and title are translatable.
With the following code:

$node = Node::create(['type' => 'my_type', 'title' => 'My title', 'langcode' => 'en', 'status' => 1, 'uid' => 1]);
$node->field_image->appendItem(['target_id' => $fid, 'alt' => 'My title']);
$node->save();

$node_t = $node->addTranslation('fr', ['title' => 'Mon titre']);
$node_t->field_image->alt = 'Mon titre';
$node_t->save();

I get the following error on save:
[error] InvalidArgumentException: Invalid translation language (und) specified. in Drupal\Core\Entity\ContentEntityBase->getTranslation() (line 873 of /data/sites/web/belvenbe1907/dev/web/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

In SqlContentEntityStorage.php line 847:

Invalid translation language (und) specified.

In ContentEntityBase.php line 873:

Invalid translation language (und) specified.

I tried several things - one more convoluted than the next, based on what I could I find online, but this seems unsolvable.

💬 Support request
Status

Closed: outdated

Version

9.3

Component
System 

Last updated 7 days ago

No maintainer
Created by

🇧🇪Belgium stevendeleus

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇧🇪Belgium Seppe Beelprez

    Together with Pathauto, if you still save the translated node after the original node is saved, the url alias is being generated as well:

    $node->save();
    $node_translation->save();
Production build 0.71.5 2024