Search code examples
phpapidrupalfielddrupal-7

How should I get the value contained in a particular field of a Drupal 7 custom node?


What is the "proper" way to get the value stored in a particular field within a custom Drupal node? I've created a custom module, with a custom node, with a custom URL field. The following works:

$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'];

...but is there a better way, maybe using the new Field API functions?


Solution

  • node_load() then accessing the field as a property is the proper way, although I'd do it slightly differently to avoid hard-coding the locale:

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

    The method you're using to get the nid is a particularly kludgy way to derive it; I'd focus on refactoring that and use EntityFieldQuery and entity_load() instead:

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

    You'd want to do this especially since title is not a unique property and if the field appears on entities other than nodes. In that case you'd remove the entityCondition().