1

I'm trying to get a list of all of a specific content type, but my entityQuery is only returning the original language of the site (English). Here's my code:

  public function fetchDocumentReferenceOptions() {
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'document')
  ->condition('langcode', $language)
  ->sort('title', 'ASC');

$nids = $query->execute();

$nodes = node_load_multiple($nids);

$options = [];

foreach($nodes as $node)
{
  // check if the document (content type) has an uploaded file
  if ($node->field_document->entity) {
      $options[$node->id()] = $node->getTitle();
  }
}

return $options;

}

This is how I call the function:

'#options' => $DocumentReferenceCore->fetchDocumentReferenceOptions(),

What I am expecting, based on condition for langcode would be that, if, for example, I am editing a Chinese language node (translated from the original English node), I should see Chinese nodes, and the content being returned, but instead I am still seeing the original English content.

What am I doing wrong here?

  • Your code should work, i have tested it i works perfectly, but i just call the function directly not in some form #options' => ... , try to dump the $language and se if it's the right language ! the condition is right. – berramou Oct 8 '18 at 21:40
3

Content entities have an active language concept. If load them, they by default return values for the default translation.

With your query, you know it has that translation, so you can do $node = $node->getTranslation($language);. If you're not sure it exists, you can use $custom_tag = \Drupal::service('entity.repository')->getTranslationFromContext($node, $desired_langcode);. That will return the node in the matching translation if it exists, or the best alternative. You can also leave out the langcode, then it defaults to the current content language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.