So basically, I'm trying to display a list of nodes that references the current node.

I'm making each node about a person. I made node reference fields to enter in each persons mother and father. Now I want to display each person's children based on the mother/father fields.

I was able to get a list of the right nodes using a view to filter nodes based on the nodereference fields... but I have to select a specific parent node to get the list from. I want it to automatically get the right parent node from the current node...

I'm pretty new to drupal and I dont think I'm that good on explaining so sorry if this is confusing... Can anyone help?

Comments

Ejaboneta’s picture

Just thought I'd bump this up to the top once more... can anyone help?

zirvap’s picture

I finally figured out how to do this for my own site, after a couple of afternoons of gnashing of teeth.

I have nodes for games, and nodes for persons. The person nodes have node reference fields which refer to the game nodes. (I'm using this for people who want to register for games at a game convention. For various reasons I didn't want to use the signup module.)

I create a view with:

  • Provide block
  • The fields I want to show (obviously :-)
  • Argument: Node reference
  • Argument handling code: $args[0] = arg(1); (Thanks to a comment from Paul Resnick here)

I go to the block administration page, activate the block, and choose that it should only be shown on the nodes that hold games.

And voila! At the bottom of my game page, there's a nice little list of all the people who have registered for that game.

Hmm, it occurs to me that it will be a lot of bother to specify where the block shall be displayed for all relevant pages. If I remember correctly, I've seen a module for CCK Viewfields which should automate this nicely. Or perhaps I'm better off with a PHP snippet...
* strolls over to the Handbook, happily whistling *

Ejaboneta’s picture

You are amazing. Thanks!

gmclelland’s picture

zirvap

How can you add a game on the "person add form"?

Is this possible?

Is there a way to add and reference at the same time?

Thanks for your help.

JonSTeps’s picture

this code works perfect and zirvap you are a life saver!

Anonymous’s picture

How would you create a this views block that contains multiple node reference arguments?

TIA,
txcrew

zirvap’s picture

The views blocks I made only had one node reference argument. I made several blocks with one node reference argument each. (Heh, that sounds cryptic even to myself. Tell me if you'd like a more detailed description.)

Anonymous’s picture

In my case, I have about 11 Node Reference fields in my content type (see http://drupal.org/node/201815 for my scenario) and I was hoping there may be a better way to do it. Perhaps just editing that Argument Handling Code to accomdate for multiple for one or more of one of the arguments that are selected. But alas, I have very limited programming knowledge and from what I have been researching so far, it doesn't seem very possible.

Does your method have any impact on performance? Any more or less than having one view with several arguments?

Thanks for the reply!

txcrew

zirvap’s picture

I have six node reference fields, which means it wasn't too much of a hassle to make a view for each. I haven't looked at performance at all. The scope of the site is pretty small (a yearly game convention with about 100-150 participants), so performance isn't much of an issue.

bsuttis’s picture

UPDATE: Sorry, I figured out the issue myself, 2 of my db tables were out of sync.

fallenleaf’s picture

THANK YOU VERY MUSH!
It works for me.
The sample website (Chinese):
http://www.buyerjoy.net/shop/761 and http://www.buyerjoy.net/brand/627 refers each other
--------------------
BUYERJOY

FiNeX’s picture

I cannot configure views2 (on D6) following your suggestion. Need I to do in a different way?

FiNeX’s picture

I've solved it on D6 with views2. I wanted to show (on a block) all nodes which had the current node referenced.

  1. Add the node_refence as argument
  2. Set "Action to take if argument is not present:" to "Provide default argument"
  3. Set "Default argument type:" to "Node ID from URL"
  4. Set "Basic Validation"

This allow me to solve this problem :-)

Simply amazing :-)

sk_mamp_nb’s picture

I wish I had come to this earlier, Thanks. This is really good.

sheclimber’s picture

I've been reading about this for 6 hours and getting more and more confused. I am very new to php, so maybe that's my problem. I'm using D6, views2. I have a content type called projects, and a content type called testimonials that has a node reference to projects. I want to use views to create a block on the project node pages that displays all the testimonials for a particular project. I tried the above, plus many other guesses, some of which were informed by reading about D5 solutions, but nothing is working.

Any help would be greatly appreciated.

FiNeX’s picture

I know that working with references could not be always easy. Are you still in trouble? Maybe after 1 year I'm a bit late... tell us if you still need help

JThan’s picture

THX FiNeX

Works perfect. Just what I needed.

Tutu’s picture

It realy works, my case D6.1-whatever + views2.
Essential things as table relationships must be simple to figure out. So it does.

nally’s picture

Please let me add my Thanks to the Chorus of others here.

Thanks!

Christian Nally - B.C., Canada - http://sticksallison.com

ecc’s picture

Your solution works perfectly... is the best I've read in this respect.

DrupalSza’s picture

Don't know how you did it... But is solid.

Thank you.

FiNeX’s picture

well, I'm happy my solution did help you all :-)

Darrin Southern’s picture

FiNeX - my thanks to you also.

UNarmed’s picture

Pure awesomeness! Almost created a whole monstrosity with views and panels and turns out the solution was so simple =] thanks a bunch!

wropul’s picture

It's hard to believe the solution is so easy ! Thanks a lot !
With this method, I made it work perfectly on drupal 7 with dev version of "reference" (2011-Aug-31 ). (This version already include "reverse" function but I can not make it work.) After failed with "Corresponding Node References" "back reference", finally I found this post.
I just want to know why it can work without "reverse" function ? I'm really confused.

operations’s picture

It didn't work with me on drupal 6 .. I'm not sure why!

$args[0] = arg(1);

However, I followed this tutorial and it worked like a charm:
http://drupalsn.com/learn-drupal/drupal-tutorials/creating-dynamic-block...

Wolf_22’s picture

Above link is dead.

operations’s picture

Why?

zirvap’s picture

Deleting duplicate post.

gmclelland’s picture

Yes it can be done? How would you do it?

Rowanw’s picture

Use CCK to add a Node Reference field to the 'person' content type, then when you create 'person' content you'll be able to select an existing node to reference.

gmclelland’s picture

The problem is that you can't add a person from the create game form or vice versa. You can only reference a record if it has already been created.

I sort of have the same problem here and here.

Maybe someone could help me out.

encho’s picture

Anyone have it working on Drupal 6?

lelizondo’s picture

I would like to know how to do this on drupal 6 too?

thanks

Luis

Luis

faunapolis’s picture

Argument: Node Reference does not show as one of the options. Thanks

http://www.faunapolis.org/

faunapolis’s picture

I asked the CCK module developer, and he very promptly answered.

The newer development version has the solution, please see:
http://drupal.org/node/265958

the alpha version of CCK for D6 did not have the option incorporated yet

http://www.faunapolis.org/

encho’s picture

Based on http://drupal.org/node/259845, finally got it working.

1. Created a relationship,
2. Argument Node:nid, using relationship,
3. Also had to use page/attachment type of view as blocks can not pass arguments, as far as I know,
4. Did other settings, like fields, filters, etc,
5. Used print views_embed_view(my_view_name, $display_id = 'attachment', arg(1));
6. Worked!

Hope this helps someone.

boulwarek’s picture

I have been trying to figure out how to basically add the functionality of nodereferrer to Drupal 6 since the module has not been ported yet, and I would have no clue on how to help port it. After tons and tons of searching and fiddling I finally got exactly what I was looking for out of your method. I did not even create a block view, only an attachment since I had no need to have it displayed in a block.

Also just for reference, I was not sure where I was supposed to put the PHP code, but finally figured out that I had to create a .tpl.php file for the content type and add it using this method: http://drupal.org/node/17565

Thank you so much for this.

matherion’s picture

Hey all,

I've been looking for what I think is the same thing, and recently, somebody created it!!! Check this post about the Nodereferrer field in Drupal 6!

Matherion

drupalninja99’s picture

i think this is perfect (I'm using drupal 5), works great for me

no2e’s picture

(subscribing)

dan_aka_jack’s picture

Many thanks for all the hints above. Using the guides above, I've created a very simple view in View2 which displays the "reverse node reference" list in a block. I thought I'd export it here:

$view = new view;
$view->name = 'reverse_node_reference';
$view->description = 'Provides a list of nodes which reference the current node in its node-reference field';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
  'title' => array(
    'label' => '',
    'link_to_node' => 1,
    'exclude' => 0,
    'id' => 'title',
    'table' => 'node',
    'field' => 'title',
    'relationship' => 'none',
  ),
));
$handler->override_option('arguments', array(
  'field_node_reference_nid' => array(
    'default_action' => 'default',
    'style_plugin' => 'default_summary',
    'style_options' => array(),
    'wildcard' => 'all',
    'wildcard_substitution' => 'All',
    'title' => '',
    'default_argument_type' => 'node',
    'default_argument' => '',
    'validate_type' => 'none',
    'validate_fail' => 'not found',
    'break_phrase' => 0,
    'not' => 0,
    'id' => 'field_node_reference_nid',
    'table' => 'node_data_field_node_reference',
    'field' => 'field_node_reference_nid',
    'relationship' => 'none',
    'default_options_div_prefix' => '',
    'default_argument_user' => 0,
    'default_argument_fixed' => '',
    'default_argument_php' => '',
    'validate_argument_node_type' => array(
      'blog' => 0,
      'poll' => 0,
      'forum' => 0,
      'book' => 0,
      'event' => 0,
      'feed' => 0,
      'page' => 0,
      'simplenews' => 0,
      'story' => 0,
      'video' => 0,
    ),
    'validate_argument_node_access' => 0,
    'validate_argument_nid_type' => 'nid',
    'validate_argument_vocabulary' => array(
      '1' => 0,
      '3' => 0,
      '2' => 0,
    ),
    'validate_argument_type' => 'tid',
    'validate_argument_php' => '',
  ),
));
$handler->override_option('filters', array(
  'status' => array(
    'operator' => '=',
    'value' => '1',
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'status',
    'table' => 'node',
    'field' => 'status',
    'relationship' => 'none',
  ),
));
$handler->override_option('access', array(
  'type' => 'none',
));
$handler->override_option('title', 'Related items');
$handler->override_option('style_plugin', 'list');
$handler->override_option('style_options', array(
  'grouping' => '',
  'type' => 'ul',
));
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);
lelizondo’s picture

maybe it would be a better choice to move it to the docs

Luis

Luis

Blueeeeie’s picture

So far all the success stories here are talking about creating a block view. What about page view?

Based on the info provided by everyone here, I was able to create a block and display it on the current node, with all the referencing nodes displaying correctly.

But I also wanted to show a page with all the referencing nodes based on the current node as well.

For example, I have a Shop and a Product node, with the product node referencing the shop node.
On my shop page (eg. shop/some-shop), I added the block to show all the referencing products, displaying only up to about 9 products. No problems there. But I wanted a dedicated page for each shop to be able to show its referencing products as well.

So I added a Page and had input all the same settings for the block, including a path for the page (shop/%/products). Funny thing is, the page won't show if I enter the url shop/some-shop/products. It only shows if I enter shop/1/products, 1 being the shop nid.

So anyone has any ideas on how to get this to work?

---
www.drupaldiy.com - Showcase your Drupal site

sagannotcarl’s picture

Hey dan_aka_jack,
Thanks for posting your view here. I imported it and tried it out but it didn't do what I was expecting.

Apologies if I just confused but this seems to be doing a normal node reference view rather than a reversed on. If I pass the view the argument of the node that is referenced in the node reference field, the view returns nothing. When I pass the nid of the node that is doing the referencing, the referenced node shows up (just like a normal node reference view would).

So am I missing another step here besides importing your view?

doomed’s picture

Check this http://drupal.org/project/nodereferrer

It might do what you want.

thaddeusmt’s picture

Seems to do the same sort of thing:

http://drupal.org/project/cnr

cookiesunshinex’s picture

subscribe

naught101’s picture

scarer’s picture

I used some code in a block to print the nodes that reference the current node being displayed:


//current project nid
$projectnid = arg(1);

/* This section checks to see if the project nid matches the project nid value referenced by a project risk
 * If it matches the risk id is printed linked to the risk
*/

// array to store the results in
$items = array();

//query the database
$result = db_query("SELECT ctpr.nid, n.title FROM {content_type_project_risk} ctpr JOIN {node} n ON ctpr.nid = n.nid WHERE ctpr.field_risk_project_nid = '$projectnid'");

while ($row = db_fetch_object($result)) {
  $items[] = l($row->title, "node/{$row->nid}");
}

// print the results
return theme('item_list', $items);

You'd just have to modify the values to suit your needs.

Hope this helps someone.

brynbellomy’s picture

Check out the Partners module: http://drupal.org/project/partners
It does backreferences like you're describing. It can also automatically generate intermediary nodes, which are nodes that contain information about the relationship between two other nodes (for example, you have a Member type that has multiple nodereferences to various Group nodes, and then perhaps a Membership node type which contains information about those relationships). There's some basic Views integration as well, so you don't have to write custom SQL.

StephenRobinson’s picture

markus_petrux’s picture

Doubt is the beginning, not the end of wisdom.

milehighlife’s picture

So, having the ability to view the referenced nodes is good. Can we go a step further and have the ability to rearrange the order of the referencing nodes?

I have a Gallery node which has several Photos that reference the gallery. I'd like to be able to view the photos referenced in the gallery and be able to rearrange the order in which the photos appear via drag-n-drop.

Anyone aware of a (current) module that accomplishes this?

Thanks!

asad.hasan’s picture

One photo only references one gallery, so where does the drag and drop comes into play.

If you did it like one gallery referencing many photos, then u could have dragged the order of those photos, oh well in that case u would have to worry about reverse reference too.

An approach u can take is adding a weight field on the photos, but it will come out to be a cumbersome way of management.

subu.purohit’s picture

Hi,
I have two related content types Artist and Movie. Movie content type has node reference to artist (Movie content type has a list of all artists).I can list all artists related to a movie in node-movie.tpl . But how can I list all movies related to an artist in node-artist.tpl?

Thanks
Subhash

asad.hasan’s picture

Create and Install the module i have posted, and then all the parent nodes will be available in a field named 'field_parent_nodes', so u can use the following code to iterate over all the parent nodes inside you node.tpl.php

  if(isset($node->field_parent_nodes)) {
      foreach($node->field_parent_nodes as $p_node) {
           //Print what ever u want from this parent $p_node in what ever fashion u like
      }
  }

I move such code into a function residing in my template.php and call it from my node-WHATEVER.tpl.php for a theme and logic seperation.

asad.hasan’s picture

Here is a zipped version of my module:

http://www.dadesigners.com/drupal-modules/da_reverse_reference.zip

i will be posting it on the contrib soon...thanks

cookiesunshinex’s picture

@asadpakistani

I'm interested in your module, but have a slight concern about duplication. I know that you mentioned another module (http://drupal.org/project/reverse_node_reference), but are you sure that your module's code could not be somehow integrated into the existing module? How is your module different than reverse node reference and how is it better?

If you think it should still be a different module, please post here when it is part of the drupal.org module contrib repository.

It would be interesting to see how your module works and I have a very big need for this on a few projects, but haven't figured out how to do it with http://drupal.org/project/reverse_node_reference.

Thanks.

asad.hasan’s picture

Ive written the following module. This adds the parent object nodes to the child node. This information can then be accessed in the theme tpl for the child node type and displayed as desired.

I realise there is a module out there (http://drupal.org/project/reverse_node_reference), but this approach seems more flexible, and easy to me.

function da_reverse_reference_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
	if($op == "load") {
		$attributes = array();
		foreach(content_fields() as $field) {
			if(isset($field["referenceable_types"]) && $field["referenceable_types"][$node->type] === $node->type) {
				$sql = "SELECT nid FROM {content_".$field["field_name"]."} WHERE ".$field["field_name"]."_nid = %d";
				$parents = db_query($sql, $node->nid);
				while($parent = db_fetch_object($parents)) {
					$attributes["field_parent_nodes"][$parent->nid] = node_load($parent->nid);
				}
			}
		}
		return $attributes;
	}
}
eracings’s picture

Thanks for your help

jonardern’s picture

I had some trouble following this at first using views 2 and Drupal 6. However after a bit of trial and error I got there, big thanks to everyone above.
This is what I did step by step to get a list of node titles that reference the node being viewed.

1. create a node view

2. add a relationship and choose node reference field under the content grouping, mark this as required.

3. add an augment for node id, under the node grouping.
3.1. under "Relationship:" choose the node reference field
3.2. "Action to take if argument is not present:" = "Provide default argument"
3.3. "Default argument type:" = "Node ID from URL" leave all other the argument options as they are.

4. Under Filters choose Node: Type = "the node type that is doing the referencing"

5. Under Fields choose Node Title and check "link this field to its node.

Lastly create a block display to place on the node page, or as i'm using display suit module, create a "node content" display.

Hope this is of help to someone .

dvmoc’s picture

Thanks jonardern, still getting the hang of relationships/arguments, and this is exactly what I was looking for! Works great, and I'm understanding things a little better now.

Cheers!

mErilainen’s picture

This works nicely also in Drupal7, I'm using Views dev-version, but should work with rc1 also.
The only difference is that after you add the referencing field as a relationship, you need to use this relationship in the "Contextual filters" setting (Content: ID -> Provide default value -> Content ID from URL).

After that you can list fields from the content type which has the referencing field without any further required relationships.

hessam61’s picture

Thanks a lot!! Worked like a charm in D7, and Views 3. In my case I skipped 3.2, setting up "Action to take if any argument is not present".

Nico7’s picture

Jonardern,

Thank you very much for summarizing this! It helped me a lot.