【问题标题】:How to get the first image field from a node without knowing the field's name?如何在不知道字段名称的情况下从节点获取第一个图像字段?
【发布时间】:2011-07-11 21:09:14
【问题描述】:

我正在开发的网站使用多种内容类型,并且几乎所有内容类型都使用一个或多个图像字段。 图像字段在内容类型之间不共享,因此数量很多。

我需要从节点获取第一个图像字段,假设有更多图像字段链接到节点并且不知道这些字段的名称。第一个被认为是weight 较低的那个。

【问题讨论】:

    标签: drupal drupal-6 imagefield


    【解决方案1】:

    这应该为每个内容类型构建一个“最轻”图像字段的数组。

    <?php
    module_load_include('inc', 'content', 'includes/content.node_form');
    $content_types = array('page', 'story', 'product', 'some_content_type');
    
    $lightest_imagefields = array(); // arranged by content type
    foreach ($content_types as $content_type_name) {
      $content_type_data = content_types($content_type_name);
      $last_weight = NULL;
      foreach ($content_type_data['fields'] as $field_name => $field_data) {
        if ($field_data['widget']['type'] == 'imagefield_widget' && (is_null($last_weight) || (int)$field_data['widget']['weight'] < $last_weight)) {
            $lightest_imagefields[$content_type_name] = $field_name;
            $last_weight = (int)$field_data['widget']['weight'];
        }
      }
    }
    /** Hypothetical Usage:
     * $node = load_some_node_i_want();
     * $node->$lightest_imagefields[$node->type]; // Access this node's lightest imagefield.
     */
    

    然后,当您加载“产品”内容类型的节点时,您知道哪个图像字段最轻(即$node-&gt;$lightest_imagefields[$node-&gt;type])。

    希望对您有所帮助。 (不过,在使用之前先测试一下!)

    【讨论】:

    • 其实我并没有测试代码,而是理解了它的逻辑,所以我现在可以毫无问题地构建自己的代码。谢谢!
    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多