Drupal paragraphs – get translation’s field values

I’m working with a client that requested me to update their Drupal’s theme, and together with that it came a surprise, a custom module that does display data on a map.

The custom module make use of paragraphs, each sub element contains relative coordinates, a title, and a few other fields.

Pretty cool! And I was able to “fix” it in order to look exactly as the client wanted…

Anyhow, onto the point.

Getting the correct translation

I thought it was something easier, but it took me a few hours of google and stackexchange.

This page helped me understand a bit more how it works, and with that I was able to get the page’s translated field.

To extract the keypoint, you will have to use this code to get the same object but with the right translation:

$paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph, $langcode);

To give a bit of context, this code is inside the paragrap’s preprocess hook:

function hook_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $langcode = $paragraph->language()->getId();

  switch($paragraph->getType()) {
    case 'my_paragraph_field':
      $translatedParagraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph, $langcode);

....

}

Something like that.

Posted in Web Development and tagged , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.