7

I have a content type available in FR and in EN.

In hook_node_presave(), I would like to concatenate the French title and the English title in another field. (This is an "helper field" which contains concatenate strings to be used by a filter in a view.)

This is my code.

function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_title1=$entity->getTitle(); //It is the French title if the saved node is the french node.
  $entity_title2= '?'; //HERE IS MY PROBLEM: how to get the title in the other language?
  $entity->my_helper_field->setValue("$entity_title1 $entity_title1");
}

How do I get the translated title of a node?

12

You should load the translated entity, and get the title from that.

$translated_entity = $entity->getTranslation('en');
$translated_title = $translated_entity->getTitle();

You can get the current entity language using $entity->get('langcode')->value;, and as @4k4 says, you should check that a translation exists using $entity->hasTranslation($langcode);.

  • Many thanks. But how to know the current language of the entity? For example, if I save an English entity, I would like to get the french title. – Baud Mar 22 '18 at 17:13
  • @Baud - with GetTranslationFromContext drupal.stackexchange.com/a/145747 – leymannx Mar 22 '18 at 19:38
  • I've improved my answer. – Matteo Palazzo Mar 23 '18 at 9:35
5

The current language of the entity is not so important, because you can get the same language again. More important is to check if the entity has the translation so that you don't get an error:

 $title_en = $entity->hasTranslation('en') ? $entity->getTranslation('en')->getTitle() : '';
 $title_fr = $entity->hasTranslation('fr') ? $entity->getTranslation('fr')->getTitle() : '';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.