【问题标题】:Displaying field collections loop in Content Type TPL file for drupal 7在 drupal 7 的内容类型 TPL 文件中显示字段集合循环
【发布时间】:2015-07-01 14:45:02
【问题描述】:

我有一个在 Drupal 7 中创建的内容类型“about”。我有一个名为“field_usf_projects”的字段集合,它设置为无限制并包含 2 个字段,“usf_title”和“usf_description”。现在我想运行一个 for 循环来检索 field_usf_projects,然后在 ul - li 结构中显示 2 个字段,即(“usf_title”和“usf_description”)。

我浏览了许多链接,但找不到可行的解决方案。请帮我解决这个问题。

提前致谢。

【问题讨论】:

    标签: drupal collections drupal-7 field


    【解决方案1】:

    这是我的解决方案,在 hook_node_view 上,您可以使用实体包装器来获取字段

    function mymodule_node_view($node, $view_mode, $langcode) {
      // Check if the node is type 'about'.
      if ($node->type != 'about') {
        return;
      }
    
      // Get the contents of the node using entity wrapper.
      $node_wrapper = entity_metadata_wrapper('node', $node);
    
      // Get the contents of the field collection.
      $values = $node_wrapper->field_usf_projects;
    
      // Loop field_usf_projects.
      foreach ($values as $item) {
        // Print the values of the fields.
        var_dump($item->usf_title->value());
        var_dump($item->usf_description->value());
      }
    }
    

    您可以为您的

    添加标记,而不是转储
  • 更好的做法是使用 hook_preprocess_node 将标记直接添加到 $variables 中,并通过模板打印出来。

    https://api.drupal.org/api/drupal/modules!node!node.module/function/template_preprocess_node/7

  • 【讨论】:

    • 你好马塞洛,我没有得到设置的字段。当我打印值数组时,我得到以下输出。查看pastebin.com/aM8sVNdN让我知道。
    【解决方案2】:

    我可以告诉你我是如何处理这个的,如果它有点脏,我冒着被钉在十字架上的风险,但它对我有用。如果您在节点模板内,则您有 $node 对象。使用print_r 或类似方式打印它,然后按照输出结构获取您的数据。大概是这样的:

    $node->field_usf_title['und']...
    

    如果您没有该 $node 对象,请查找节点 ID 并使用

    加载该节点
    $node = node_load($nid);
    

    首先。

    【讨论】:

    • 我没有得到这些字段。另外,当我打印出数组时,以下是我得到的pastebin.com/vt5cg5vx
    • 但就是这样。在某些情况下,您可以使用所有节点字段,但在某些情况下您没有。但是你有“nid”字段,所以你可以自己加载整个节点,正如我上面解释的那样。所以,$node = node_load($node->nid);你会得到完整的节点。
    【解决方案3】:

    我终于厌倦了 Field 收集。我无法获得任何数据。我使用了 Multifield,它比 Field 集合好太多了。请查看https://www.drupal.org/project/multifield

    让我知道什么是更好的多字段或字段集合。

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2017-01-31
      • 2017-11-13
      • 2011-05-20
      • 2012-03-01
      • 2021-04-23
      相关资源
      最近更新 更多