【问题标题】:How should I get the value contained in a particular field of a Drupal 7 custom node?我应该如何获取 Drupal 7 自定义节点的特定字段中包含的值?
【发布时间】:2011-01-17 02:14:57
【问题描述】:

获取存储在自定义 Drupal 节点中特定字段中的值的“正确”方法是什么?我创建了一个带有自定义节点的自定义模块,带有自定义 URL 字段。以下作品:

$result = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(
  ':title' => $title,
  ':type' => 'custom',
))->fetchField();
$node = node_load($result);
$url = $node->url['und']['0']['value'];

...但是有没有更好的方法,也许是使用新的 Field API 函数?

【问题讨论】:

    标签: php api drupal field drupal-7


    【解决方案1】:

    node_load() 然后将字段作为属性访问是正确的方法,尽管我会稍有不同以避免对语言环境进行硬编码:

    $lang = LANGUAGE_NONE;
    $node = node_load($nid);
    $url = $node->url[$lang][0]['value'];
    

    您用来获取 nid 的方法是一种特别笨拙的派生方法;我将专注于重构并改用EntityFieldQueryentity_load()

    $query = new EntityFieldQuery;
    $result = $query
      ->entityCondition('entity_type', 'node')
      ->propertyCondition('type', $node_type)
      ->propertyCondition('title', $title)
      ->execute();
    
    // $result['node'] contains a list of nids where the title matches
    if (!empty($result['node']) {
      // You could use node_load_multiple() instead of entity_load() for nodes
      $nodes = entity_load('node', $result['node']);
    }
    

    您会希望这样做,特别是因为 title 不是唯一属性,并且如果该字段出现在节点以外的实体上。在这种情况下,您将删除 entityCondition()

    【讨论】:

    • 感谢您的反馈!你知道一个更好的方法来获得nid,只给一个节点的标题吗?
    • @Matt 我会使用EntityFieldQuery 和实体API,特别是考虑到字段可以出现在节点以外的东西上。我已经用一种可能的重构方式更新了我的答案。
    【解决方案2】:

    不确定为什么要讨论 EntityFieldQuery,但可以。 :) 你实际上会想要使用field_get_items() 函数。

    if ($nodes = node_load_multiple(array(), array('type' => 'custom', 'title' => $title)) {
      $node = reset($nodes);
      if ($items = field_get_items('node', $node, 'url')) {
        $url = $items[0]['value'];
        // Do whatever
      }
    }
    

    【讨论】:

    • EntityFieldQuery 正在讨论中,因为您在代码 is deprecated 中使用的 node_load_multiple() 的条件参数有利于 EntityFieldQuery。而field_get_items() 与将字段作为节点上的属性访问完全相同的事情还有很长的路要走。
    • 该参数确实已被弃用,但node_load()仍在使用它。它可能不会在 Drupal 8 上使用,但我认为在 Drupal 7 上使用它是安全的。
    【解决方案3】:

    propertyCondition('field_order_no', 'value', '搜索键', '=')

    field_order_no 是自定义字段的 slug & Search Key 是要匹配的值

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2015-10-10
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多