How do I get the value contained in a specific field of a custom Drupal 7 node?

What is the โ€œrightโ€ way to get the value stored in a specific field in a custom Drupal node? I created a custom module with a custom node with a custom url. 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, perhaps using the new field API functions?

+4
source share
3 answers

node_load() , then accessing the field as a property is the correct way, although I would do it a bit differently to avoid hard-coding locales:

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

The method that you use to get nid is a particularly clone way to get it; I would focus on refactoring 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 would like to do this, especially because the name is not a unique property, and if the field appears on objects other than nodes. In this case, you will remove entityCondition() .

+6
source

I donโ€™t know why EntityFieldQuery is being discussed, but fine. :) You really 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 } } 
+1
source

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

field_order_no is the custom field pool, and the search key is the value that needs to be mapped to

-1
source

Source: https://habr.com/ru/post/1335780/


All Articles