Jawaban:
Gunakan kode berikut:
$curr_langcode = \Drupal::languageManager()->getCurrentLanguage(\Drupal\Core\Language\LanguageInterface::TYPE_CONTENT)->getId();
// retrieve term
$taxonomy_term = \Drupal\taxonomy\Entity\Term::load($tid);
// retrieve the translated taxonomy term in specified language ($curr_langcode) with fallback to default language if translation not exists
$taxonomy_term_trans = \Drupal::service('entity.repository')->getTranslationFromContext($taxonomy_term, $curr_langcode);
// get the value of the field "myfield"
$myfield_translated = $taxonomy_term_trans->myfield->value;
Anda harus (harus) menggunakan layanan alih-alih di baris pertama untuk language_manager. Saya juga akan mempersingkat kode dengan menggunakan tag penggunaan.
Di suatu tempat di awal file:
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Language\LanguageInterface;
dan kemudian dalam kode di beberapa fungsi
$curr_langcode = \Drupal::service('language_manager')->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
// Retrieve term.
$taxonomy_term = Term::load($tid);
// Retrieve the translated taxonomy term in specified language
// ($curr_langcode) with fallback to default language if translation not
// exists.
$taxonomy_term_trans = \Drupal::service('entity.repository')->getTranslationFromContext($taxonomy_term, $curr_langcode);
// Get the value of the field "myfield".
$myfield_translated = $taxonomy_term_trans->myfield->value;
Cuplikan di atas akan mengembalikan istilah yang tidak diterjemahkan juga. Anda harus memeriksa apakah suatu istilah diterjemahkan dengan fungsi hasTranslation:
$vocabulary = 'MY_VOCABULARY_NAME';
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary);
$query->sort('weight');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
$termList = array();
foreach($terms as $term) {
if($term->hasTranslation($language)){
$translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
$tid = $term->id();
$termList[$tid] = $translated_term->getName();
}
}
// To print a list of translated terms.
foreach($termList as $tid => $name) {
print $name;
}
Untuk menautkan tag ke halaman istilah mereka: Lihat: Dapatkan istilah taksonomi