【问题标题】:How to get value of multiple values field in Drupal 8?如何在 Drupal 8 中获取多个值字段的值?
【发布时间】:2017-04-16 19:27:27
【问题描述】:

我在 Drupal 8 中有多个值图像字段,我想在 Controller 中准备值以在 twig 模板中输出。

对于单值字段来说,这很简单(好吧,如果我们可以将复杂得可笑的 “lets-do-everything-in-OOP-eventhough-its-useless”称为 Drupal 8 方式简单):

$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',
);

但是,field_fotografie 值是多值字段,我想在$data 数组中获取所有图像的 URI。有人知道怎么做吗?理想情况下,少于 10 行无用的 OOP jibber-jabber。谢谢。

【问题讨论】:

    标签: drupal-8


    【解决方案1】:

    这样试试,可能对你有用。

    $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,
      );
    }
    

    【讨论】:

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

      希望对你有帮助 谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-29
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多