Drupal Views / Node Reference get parents relation

1.7k views Asked by At

Ok, sorry for that title, it´s hard to describe. My problem is the following: I have the Content Types "Product Category" (don´t using Taxonomy for this for several reasons) and "Product". Products are referenced to their Category using Node Reference.

I also have a View which displays, on the Category page, all belonging Products using a Contexual Filter => "Node-ID from URL". My problem is now, when I click on a Product, i need to keep the relation. The contextual filter of course doesn´t know the NID of the Product Category anymore, because the current NID is the one from my Product.

Works: /category/xyz
Works not: /category/xyz/myproduct (because i need the nid of "xyz", not "myproduct")

Does anyone know how i tell the contextual filter to get the NID of the parent Category?

2

There are 2 answers

4
Rick Donohoe On

Not sure if I totally understand, but when you use contextual filters such as Node ID from URL, you can select which argument to use.

In the case of this relative URL /category/xyz/myproduct, arg 1 refers to 'category' and arg 2 refers to 'xyz'

Maybe have a view setup for /category/* and /category/xyz/* and then set which parts of the URL to use in the contextual filters differently.

Does that help?

Note: The arg setting should be a drop down setting from the 'provide default argument' within the contextual filters.

0
Arne Cordes On

For lack of a better solution… for the product page, i added another view display and changed it a bit:

  • I added a relationship and selected my node reference field for the category
  • I changed my contextual filter to custom PHP and provided the following code:

    $n = node_load(arg(1));
    return $n->field_product_product_category['und'][0]['nid'];
    

I don´t mark this answer as accepted, because i don´t think this is the right way. I load the node which gets loaded anyway, so i think i´m producing an unnecessary database call and all the stuff which is related to properly get a node object.

Maybe someday someone has a better answer for this.