Get the result a view creates

Last modified: January 8, 2010 - 11:29

This function has been inserted into to the Views module since v2.8.
#495606: Programming addition to Views help

Every view creates an array which contains the result of the query. Each view item has its own object inside this array. This is very handy if you want to use a view result without theming e.g. for further processing like used in Linodef (upon RC3 release).

The corresponding issue is #341880: How to get a "result Array" with views_get_view() (as with views_get_current_view()).

Investigate the result of a view

Here is a function which returns the result of a view by name. It is possible to use arguments and set a certain view display.

<?php
/**
* Investigate the result of a view.
*
* @param string $viewname
*      The name of the view to retrieve the data from.
* @param string $display_id
*      The display id. On the edit page for the view in question, you'll find
*      a list of displays at the left side of the control area. "Defaults"
*      will be at the top of that list. Hover your cursor over the name of the
*      display you want to use. An URL will appear in the status bar of your
*      browser. This is usually at the bottom of the window, in the chrome.
*      Everything after #views-tab- is the display ID, e.g. page_1.
* @param array $args
*      Array of arguments.
* @return
*      array
*          An array containing an object for each view item.
*      string
*          If the view is not found a message is returned.
*/
function views_get_view_result($viewname, $display_id = NULL, $args = NULL) {
 
$view = views_get_view($viewname);
  if (
is_object($view)) {
    if (
is_array($args)) {
     
$view->set_arguments($args);
    }
    if (
is_string($display_id)) {
     
$view->set_display($display_id);
    }
    else {
     
$view->init_display();
    }
   
$view->pre_execute();
   
$view->execute();
    return
$view->result;
  }
  else {
    return
t('View %viewname not found.', array('%viewname' => $viewname));
  }
}
?>

Get the result for the current view:

<?php
function views_get_current_view_result() {
 
$view = views_get_current_view();
  return
$view->result;
}
?>

Heed that only the view items for the first page are returned. If the result array should contain all items then set the numbers of items per page to 0 (no limit).

Structure of the result array

The Array contains an object for each view item. Imagine a site has only one node then a node view type without fields and sort criteria would look like this:

<?php
Array
(
    [
0] => stdClass Object
       
(
            [
nid] => 1
       
)
)
?>

So by default the view item object only contains the id of the view type:

nid
Node view type
vid
Node version view type
tid
Term view type
uid
User view type
fid
File view type
cid
Comment view type

Additional the content of some view object types is added if they are defined. Those object types are:

  • Fields
  • Sort criteria

Example

Here we have a term view type with the following content:

Fields

  • Taxonomy: Vocabulary name
  • Taxonomy: Term

Sort criteria

  • Taxonomy: Weight

So the obtained result array looks like this (only one object as example given here):

<?php
Array
(
    [
0] => stdClass Object
       
(
            [
tid] => 3
           
[vocabulary_name] => Planets of Sol
           
[term_data_name] => Earth
           
[term_data_vid] => 1
           
[term_data_weight] => 0
       
)
)
?>

CCK Fields

When using CCK fields the name pattern is as following:
node_data_%first_field_name_%current_field_name_%value
where:

%first_field_name
The name of the CCK field with the lowest weight (first appearance).
%current_field_name
The name of the CCK field the value belongs to.
%value
Can be value, format etc (depends on the current field).

An example can be found here, an explanation is over here.

How to call this values

Apfel007 - March 17, 2009 - 13:11

Hi,
how can I call this results - perhaps in a view header?

..
print $view -> result[2]['nid'];.

.. this won't work

You can put this function in

eddy147 - April 9, 2009 - 07:51

You can put this function in a module or template.php for example.
I call it in my page.tpl.php like this:

$view_result = views_get_view_result($view_name);
foreach($view_result as $item){
        $node = node_load($item->nid);
        print '<h3 id="'.$node->nid.'">'.$node->title.'</h3>';
        print $node->body;
}

in this example i am selecting node id's in my view. So if your view selects something else, then you have handle accordingly.

thanx

czeky - January 29, 2010 - 18:00

I'm getting correct array output, but how to print it? (in View header)

<?php
print $view->node_data_field_dim_big_d_field_dim_big_d_value[0]['value'];
?>

doesn't seem to work

<?php
Array
(
    [
0] => stdClass Object
       
(
            [
nid] => 123457832
           
[node_title] => 6024
           
[node_language] => cs
           
[node_data_field_dim_d_field_dim_d_value] =>
            [
node_type] => single_row_ball_bearings
           
[node_vid] => 123457832
           
[node_data_field_dim_big_d_field_dim_big_d_value] => 180.000
           
[node_data_field_dim_big_b_field_dim_big_b_value] => 28.000
           
[node_data_field_blr_dynamic_cr_field_blr_dynamic_cr_value] => 85.000
           
[node_data_field_blr_stytic_cor_field_blr_stytic_cor_value] => 79.400
           
[node_data_field_lsfl_grease_field_lsfl_grease_value] => 3300.000
           
[node_data_field_lsfl_grease_field_lsfl_oil_value] => 4000.000
       
)

)
?>

Thanks this was very useful

webel - July 2, 2009 - 04:08

Example of application given here, where products from the same vendor as a featured product are listed below that product, after being gleaned from a view after the method described here, and then displayed using custom display code. Opens up lots of useful possibilities.

Webel, "Elements of the Web", Scientific IT Consultancy,
For UML, UML Parsing Analysis, SysML, Java, XML, and Drupal CMS
http://www.webel.com.au
http://www.ethicalemarket.com
http://play.webel.com.au
"See a need, fill a need", Bigweld (from "Robot

To set filter in custom view

deepM - August 24, 2009 - 22:13

To set filter in custom view call you have to write this.

$display_id='page_4';  //id of view

$view2 = views_get_view( 'View_name' ); //name of view in ui
$view2->set_display('display_id');
$view2->get_total_rows = true;

$item['value'] =array($_GET['tid']);   //set value of taxonomy id which is sent by get method in my case
$id = $view2->add_item($display_id, 'filter', 'node', 'term_node_tid_depth');    // calling add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
$item = $view2->get_item($display_id, 'filter', $id);
$view2->set_item($display_id, 'filter', $id, $item);

//execute
$view2->pre_execute();
$view2->execute();

$count2 = count( $view2->result  );  //do somethint with result, here i count number of results

Been searching this for some time, works in views 2. For names of $table and $field, look into export of view if you have created it, or make some for example to know which are proper names for variables you have to pass.

Programmatically getting the lowest weight CCK field name

mchaplin - December 11, 2009 - 11:48

I was trying to get the lowest weight CCK field name in a view. This is useful where you are using views results programmatically. I wanted make sure my code didn't break when the order of fields changed in the view.

The best I could come with was:

$view = views_get_view('your_view_name');

$displayoptions = $view->display["page_1"]->display_options["fields"];
//eg display["block_1"] eg display["page_1"] eg display["default"]

foreach($displayoptions as $key => $value){
if (substr("$key",0,6) == "field_"){
echo "Lightest CCK field: $key";
break;
}

}

TODO: move this handbook

dereine - January 29, 2010 - 19:48

TODO: move this handbook perhaps into views advanced help because this function is in views 2.8

----------------------------------------
Jabber-me: dwehner@im.calug.de

 
 

Drupal is a registered trademark of Dries Buytaert.