Mat*_* V. 4 php api drupal field drupal-7
将值存储在自定义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'];
Run Code Online (Sandbox Code Playgroud)
...但是有没有更好的方法,可能使用新的Field API函数?
小智 6
node_load()
然后作为属性访问该字段是正确的方法,虽然我做的略有不同,以避免硬编码语言环境:
$lang = LANGUAGE_NONE;
$node = node_load($nid);
$url = $node->url[$lang][0]['value'];
Run Code Online (Sandbox Code Playgroud)
你用来获取nid的方法是一种特别愚蠢的方法来获得它; 我专注于重构,并使用EntityFieldQuery
和entity_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']);
}
Run Code Online (Sandbox Code Playgroud)
你想要这样做,特别是因为title不是一个独特的属性,并且该字段出现在节点以外的实体上.在那种情况下,你将删除entityCondition()
.