以编程方式检索当前语言中的翻译分类法术语


Answers:


15

使用以下代码:

$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;

6

您应该(必须)在language_manager的第一行使用服务。我也将通过使用标签来缩短代码。

文件开头的某处:

use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Language\LanguageInterface;

然后在代码中的一些功能

$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;

2

上面的摘录也将返回未翻译的术语。您必须检查是否使用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;
}

要将标签链接到其术语页面:请参阅:获取分类术语

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.