Skip to content
Advertisement

How to access to node fields in drupal 8

I’m having some issues, I’m loading some nodes and i want to get some values field, this is how is my field

enter image description here

I’m loading my nodes like this:

$nids = Drupal::entityQuery('node')
->condition('type','items', '=')
->execute();
$nodes =  Node::loadMultiple($nids);

foreach ($nodes as $key => $node) {
  kint($node);
  $array[] = array(
    'name_item_en' => $node->get(field_name_item)->value,
  );
}

But i dont know how to get en fr and pt fields values

Could you please help me? Regards Mario

Advertisement

Answer

You can load translation for each language then get corresponding field’s value like this:

foreach ($nodes as $key => $node) {
  $array[] = array(
    'name_item_en' => $node->getTranslation('en')->get('field_name_item')->value,
    'name_item_fr' => $node->getTranslation('fr')->get('field_name_item')->value,
    'name_item_pt' => $node->getTranslation('pt')->get('field_name_item')->value
  );
}

If en is default language on your site, you may not need to load translation of it:

'name_item_en' => $node->get('field_name_item')->value
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement