materio-d9/web/modules/custom/materio_sapi/src/CountryNameNodeComputed.php

44 lines
1.8 KiB
PHP

<?php
namespace Drupal\materio_sapi;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
// use Drupal\Core\StringTranslation\TranslatableMarkup;
class CountryNameNodeComputed extends FieldItemList {
use ComputedItemListTrait;
protected function computeValue() {
$node = $this->getEntity();
$node_lang_code = $node->language()->getId();
// $distrib = $node->get('field_distributor')->referencedEntities();
// $manuf = $node->get('field_manufacturer')->referencedEntities();
$companies = array_merge($node->get('field_distributor')->referencedEntities(), $node->get('field_manufacturer')->referencedEntities());
$country_codes = [];
foreach ($companies as $term) {
$address = $term->get('field_public_address')->first();
if ($address) {
$country_code = $address->getCountryCode();
if (!in_array($country_code, $country_codes)){
$country_codes[] = $country_code;
}
}
}
if (count($country_codes)) {
$full_country_list = \Drupal::service('country_manager')->getList();
foreach ($country_codes as $i => $country_code) {
/** Drupal\Core\StringTranslation\TranslatableMarkup **/
$country_name = $full_country_list[$country_code];
// $country_name->options['langcode'] = $this->langcode;
// $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$untranslated = $country_name->getUntranslatedString();
// $translated = $country_name->render(['langcode' => $node_lang_code]);
$translated = t($untranslated, [], ['langcode'=>$node_lang_code]);
// $this->list[$i] = $this->createItem($i, "lang: $lang, node:$node_lang_code, $untranslated, $translated");
$this->list[$i] = $this->createItem($i, $translated);
}
}
}
}