Monday, 28 October 2013

Drupal 7: Referencing Views from inside Panel Pages

Example Scenario: I have created a Panel Page (e.g. Cars) and I want to display a View list of Parts associated with any Car loaded through that Panel page. Each Car node contains a reference (Entity Reference) field (field_parts_ref) to all the parts associated with it.

First, create your View, choose which fields to display, and add a context - select Content: Nid of the Car and on the next page you select Provide default value from the drop down list, select PHP Code from the drop down list, and add the following code:

//get node id of parent passed from the panel and load the node into memory
$nid = $argument->view->args[1];
$node = node_load($nid);
//read the field which has references to the node id's of the child items and add them to $refs
$refs = array();
foreach((array)$node->field_parts_ref['und'] as $t){
     if ( ! empty($t['target_id']))
         $refs[] = $t['target_id'];
}
//return the array of child item references to the view in a comma-seperated list so it displays only those items
return implode(',', $refs);


Now scroll to the bottom and expand More and check Allow multiple values. 
Now you can create your Panel Page. Add your view as a content, but when it shows the interface to configure the View you need to select the Cars ID field in the Node Being Viewed section of the drop down, and make sure the Send arguments check box is checked.

That's it. It was a little tricky to figure this stuff out but I got there in the end, so I hope this gives some clue to anyone trying to get something working.

No comments:

Post a Comment