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.

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

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 :

// 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.

= node_load($objectId); // Have fun :)