CountryNameNodeComputed.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Drupal\materio_sapi;
  3. use Drupal\Core\Field\FieldItemList;
  4. use Drupal\Core\TypedData\ComputedItemListTrait;
  5. // use Drupal\Core\StringTranslation\TranslatableMarkup;
  6. class CountryNameNodeComputed extends FieldItemList {
  7. use ComputedItemListTrait;
  8. protected function computeValue() {
  9. $node = $this->getEntity();
  10. $node_lang_code = $node->language()->getId();
  11. // $distrib = $node->get('field_distributor')->referencedEntities();
  12. // $manuf = $node->get('field_manufacturer')->referencedEntities();
  13. $companies = array_merge($node->get('field_distributor')->referencedEntities(), $node->get('field_manufacturer')->referencedEntities());
  14. $country_codes = [];
  15. foreach ($companies as $term) {
  16. $address = $term->get('field_public_address')->first();
  17. if ($address) {
  18. $country_code = $address->getCountryCode();
  19. if (!in_array($country_code, $country_codes)){
  20. $country_codes[] = $country_code;
  21. }
  22. }
  23. }
  24. if (count($country_codes)) {
  25. $full_country_list = \Drupal::service('country_manager')->getList();
  26. foreach ($country_codes as $i => $country_code) {
  27. /** Drupal\Core\StringTranslation\TranslatableMarkup **/
  28. $country_name = $full_country_list[$country_code];
  29. // $country_name->options['langcode'] = $this->langcode;
  30. // $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  31. $untranslated = $country_name->getUntranslatedString();
  32. // $translated = $country_name->render(['langcode' => $node_lang_code]);
  33. $translated = t($untranslated, [], ['langcode'=>$node_lang_code]);
  34. // $this->list[$i] = $this->createItem($i, "lang: $lang, node:$node_lang_code, $untranslated, $translated");
  35. $this->list[$i] = $this->createItem($i, $translated);
  36. }
  37. }
  38. }
  39. }