Tip of the day, get a views row primary key value

Share and options

This is often a problem when you pragmatically manipulate views row's : finding the primary key value of the current row being explored.
Let's have an example : A node base table based view.

<?php
 
// Load the view, and stick to default display for sample purpose.
 
$view = views_get_view('my_node_view');
 
$view->set_display(NULL);
 
// Then, execute it.
 
$view->pre_execute();
 
// You will set some other options here, like limit, pager, offset.
 
$view->execute();
?>

What then?

Now that your view is ready, and full of results, let's see how to manage this content. I admit, I took the easy use case, which is a node table based view, but this method will work whatever is the base table.

Now, for each row, I want to get back my node, without having to care how the view is configured, let's just trust the views_query object :

<?php
 
// The $id variable is important here, see why next:
 
foreach ($view->result as $id => $result) {
   
// The magic line!
   
$objectId = $view->result[$id]->{$view->query->base_field};
  }
?>

Now, the $objectId variable has the primary key value of the primary field used by views, for the view's given base table. Which means, in other words, for a node table based view, the current nid value.

Whatever is the display, the style plugin, the view's configuration, you will always get back the nid here.

<?php
  $node
= node_load($objectId); // Have fun :)
?>