I have a node "Bug/Requests" which references one "Project".
On the project "node" page, I would like to display a list of bugs/requests which link to that project. Is this possible?
here is how I ended up doing it:
Is this good or bad? Is there a better way? (in template.php)
<?php
function digital_preprocess_node(&$vars)
{开发者_开发百科
$node = $vars['node'];
if ($node->type == 'project' )
{
$bugs_requests_nids = array();
$query = 'SELECT entity_id FROM field_data_field_project WHERE field_project_nid = :project_nid';
$result = db_query($query, array(':project_nid' =>$node->nid));
foreach($result as $row)
{
$bugs_requests_nids[] = $row->entity_id;
}
$vars['tasks'] = node_load_multiple($bugs_requests_nids);
}
}
I think you want the References Module (provides node and user reference fields for Drupal 7)
Apologies I didn't read properly, you also want the Corresponding node reference module which makes the node reference bi-directional (D7 versions of the modules given in another answer).
EDIT to address your new code:
I'm guessing you're pretty new to Drupal from your recent questions but either way you've hit on (in my opinion) the best method to do this. If you're comfortable writing PHP code (which a lot of Drupal users aren't) then grabbing the data directly will always be more efficient than using a contributed module that might have a lot of overhead.
A few minor points:
- I'd consider moving your code out of the template file and into a custom module, inside a
hook_node_load
function instead so this data is available throughout the life of the nodes (that way you can re-use it in many different contexts). However if you don't need to reuse this data anywhere except in the template file then it's fine where it is. - If you're going to go directly into the field tables you should probably use the
field_revision_field_x
tables instead offield_data_field_x
so you can take advantage of the revision system and always grab the most recent data. - As fields can be attached to multiple entity types you should make sure you're getting the right field data for the right entity (you may not plan to attach this field to any other nodes/entities but it's good practice in case you do).
This is a slightly edited version of your code taking into account the proper field types (untested but should work):
function digital_preprocess_node(&$vars) {
$node = $vars['node'];
if ($node->type == 'project' ) {
$bugs_requests_nids = db_select('field_revision_field_project', 'p')
->fields('p', array('entity_id'))
->condition('entity_type', 'node')
->condition('bundle', 'project')
->condition('entity_id', $node->nid)
->condition('revision_id', $node->vid)
->execute()
->fetchCol();
$vars['tasks'] = node_load_multiple($bugs_requests_nids);
}
}
精彩评论