web-dev-qa-db-ja.com

プログラムで現在の言語に翻訳された分類用語を取得する

D8を使用して、現在の言語コンテキストから、翻訳された特定の分類用語を(この用語の翻訳が存在する場合)プログラムで取得するにはどうすればよいですか?

11
kxo

次のコードを使用します。

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

代わりに、language_managerの最初の行でserviceを使用する必要があります(必須)。また、useタグを使用してコードを短くします。

ファイルの最初のどこかに:

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;
6
Hannes Kirsman

上記のスニペットは、未翻訳の用語も返します。用語が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;
}

タグを用語ページにリンクするには、以下を参照してください。 Get taxonomy terms

2