Pergunta

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?

Foi útil?

Solução

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().

Outras dicas

Not sure why EntityFieldQuery is being discussed, but ok. :) You're actually going to want to use the field_get_items() function.

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
  }
}

propertyCondition('field_order_no', 'value', 'search key', '=')

field_order_no is the slug of custom field & Search Key is the value to be matched with

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top