http://hojtsy.hu/blog/2015-nov-11/drupal-8-multilingual-tidbits-19-conte...

The above page says:

// If the node has no Spanish translation, this also adds one. If it does
// already have a Spanish translation, it will update the title.
$node->getTranslation('es')->title->value = 'Spanish title';
$node->save();

I gave this a try on 8.2.4 and it yields an exception:

exception 'InvalidArgumentException' with message 'Invalid translation language (es) specified.' in
/var/www/vhosts/raystedman.org/d8.raystedman.org/core/lib/Drupal/Core/Entity/ContentEntityBase.php:745

In my case $node exists and does not have an 'es' translation prior to executing the sequence above. The website does have the 'es' language configured.

The following sequence does work in the same situation:

$node = $node->hasTranslation('es') ? $node->getTranslation('es') : $node->addTranslation('es');
$node->title->value = "Spanish $alias";
$node->save();

Please change the code to accommodate this case -- or change the tidbits-19 web page.

Comments

Greg Sims created an issue. See original summary.

Greg Sims’s picture

Component: language.module » language system
Issue tags: +D8MI
cilefen’s picture

Status: Active » Closed (works as designed)

getTranslation() is doing what it is documented to do. This change was made deliberately in #2090983: ContentEntityInterface::getTranslation() should throw an exception when an invalid language is specified.

There is not a bug to fix here. If the blog entry is wrong, add a comment.

Greg Sims’s picture

Status: Closed (works as designed) » Needs work

The implementation is not consistent with the documentation at the link in #1. We need this issue to go to Gábor. Please assign the issue to him so the blog can be updated. Thanks.

cilefen’s picture

Status: Needs work » Closed (works as designed)

No. This issue queue is not for managing non drupal.org content.

alexpott’s picture

@Greg Sims last I checked http://hojtsy.hu/blog/2015-nov-11/drupal-8-multilingual-tidbits-19-conte... has a comment box. Gabor is extremely conscientious and I'm pretty sure if you leave him a comment then he'll update the code example.

Gábor Hojtsy’s picture

Thanks everyone for notifying me. Updated the example there to:

// If the node has a Spanish translation, update the title. In case of a missing
// Spanish translation this will throw an InvalidArgumentException.
$node->getTranslation('es')->setTitle('Spanish title')->save();

Also updated the note above the page to say updated as of Jan 4th 2017 as I don't believe there are other problems that are not up to date on the page.

Greg Sims’s picture

Thanks everyone!! Greg