1

I'm on Drupal 9. I need to load the options labels of a Webform's option programmatically.

So far, I've managed to load the labels:

  $element = $webform_submission->getWebform()
      ->getElement($element_key, TRUE);

  $option_text = WebformOptionsHelper::getOptionText($element_value, $element['#options']);

However, I also need to get those labels for both the language of the site - en and it.

The webform object hasn't a getTranslation() method, so I've tried:

  • relying on $webform_submission->getTranslation($langcode), but that doesn't work, as it exists only for the language the webform was submitted

  • trying to use:

$test = \Drupal::service('entity.repository')
      ->getTranslationFromContext($webform, $langcode);
// get the options values

but that doesn't work either, the labels are always in it if the webform has been submitted in it and similarly for en.

How can get the options for both languages?

2 Answers 2

3

You need the translation manager that Webform provides (alternatively you could approach this as standard config entity translation management).

The following code demonstrates how you can display the translated labels for a Select element added to a Webform.

<?php

use Drupal\webform\Entity\Webform;

// We need the translation manager.
$wftm = \Drupal::service('webform.translation_manager');
// Get the standard contact webform, with added translated options element.
$wf = Webform::load('contact');

// Get all the system languages.
$langcodes = \Drupal::languageManager()->getLanguages();
$langcodesList = array_keys($langcodes);

foreach ($langcodesList as $langcode) {
  $elements = $wftm->getElements($wf, $langcode);
  if (isset($elements['custom_options']['#options'])) {
    var_dump($elements['custom_options']['#options']);
  }
}

The output looks sth like this:

root@b91117fbf40f:/app# drush scr webform_test.php 
array(3) {
  ["lala"]=>
  string(4) "Lala"
  ["koko"]=>
  string(4) "Koko"
  ["mimi"]=>
  string(4) "Mimi"
}
array(3) {
  ["lala"]=>
  string(9) "Lala (it)"
  ["koko"]=>
  string(9) "Koko (it)"
  ["mimi"]=>
  string(9) "Mimi (it)"
}
0

Just sligthly different from Stefanos Petrakis's answer (using getTranslationElements() instead of getElements():

$webform_translation_manager = \Drupal::service('webform.translation_manager');
$webform_translated_elements = $webform_translation_manager->getTranslationElements($booking_form, $langcode);
$options = $webform_translated_elements['element_machinename']['#options'];

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.