How to get value of multiple values field in Drupal 8?

12,121

Try like this way, it might be useful for you.

$data = array();
foreach($nodes as $node) {
  $photo = array();
  foreach($node->get('field_image')->getValue() as $file){
    $fid = $file['target_id']; // get file fid;
    $photo[] = \Drupal\file\Entity\File::load($fid)->getFileUri();
  }

  $data[] = array(
    'rocnik' => $node->get('field_rok')->getValue(),
    'miesto' => $node->get('field_miesto_konania')->getValue(),
    'fotografie' => $node->get('field_zbornik')->getValue(),
    'foto' => $photo,
  );
}
Share:
12,121
petiar
Author by

petiar

Updated on June 15, 2022

Comments

  • petiar
    petiar about 2 years

    I have multiple values image field in Drupal 8 and I would like to prepare values in Controller for output in the twig template.

    It's simple (well, if we can call the ridiculously complicated "lets-do-everything-in-OOP-eventhough-its-useless" Drupal 8 way simple) for single value fields:

    $nids = \Drupal::entityQuery('node')->condition('type', 'zbornik_a_foto')->execute();
    $nodes = Node::loadMultiple($nids);
    
    $data = array();
    foreach ($nodes as $node) {
      $data[] = array(
        'rocnik' => $node->get('field_rok')->getValue(),
        'miesto' => $node->get('field_miesto_konania')->getValue(),
        'fotografie' => $node->get('field_zbornik')->getValue(),
        'foto' => $node->get('field_fotografie')->getValue(),
      );
    }
    
    return array(
      '#theme' => 'riadky_zazili',
      '#data' => $data,
      '#title' => 'Zažili sme',
    );
    

    However, the field_fotografie value is multiple values field and I would like to get all image's URIs in the $data array. Does anybody know how? Ideally less than 10 lines of useless OOP jibber-jabber. Thanks.