Community Documentation

ARCHIVE: Advanced: Using views_build_view to control your own views

Last updated March 26, 2011. Created by joshk on November 25, 2006.
Edited by linclark, alpritt, merlinofchaos. Log in to edit this page.

Below is the views_build_view function comment.

This builds the basic view.

@param $type
  'page' -- Produce output as a page, sent through theme. The only real difference between this and block is that a page uses drupal_set_title to change the page title.
    'block' -- Produce output as a block, sent through theme.
    'embed' -- Use this if you want to embed a view onto another page, and don't want any block or page specific things to happen to it.
    'result' -- return an $info array. The array contains:
      query: The actual query ran.
      countquery: The count query that would be run if limiting was required.
      summary: True if an argument was missing and a summary was generated.
      level: What level the missing argument was at.
      result: Database object you can use db_fetch_object on.
    'items' -- return info array as above, except instead of result,
      items: An array of objects containing the results of the query.
    'queries' -- returns an array, summarizing the queries, but does not
      run them.

@param $view
   The actual view object. Use views_get_view() if you only have the name or vid.

@param $args
   args taken from the URL. Not relevant for many views. Can be null.

@param $use_pager
   If set, use a pager. Set this to the pager id you want it to use if you plan on using multiple pagers on a page. To go with the default setting, set to $view->use_pager. Note that the pager element id will be decremented in order to have the IDs start at 0.

@param $limit
   Required if $use_pager is set; if $limit is set and $use_pager is not, this will be the maximum number of records returned. This is ignored if using a view set to return a random result. To go with the default setting set to $view->nodes_per_page or $view->nodes_per_block. If $use_pager is set and this field is not, you'll get a SQL error. Don't do that!

@param $page
    $use_pager is false, and $limit is !0, $page tells it what page to start on, in case for some reason a particular section of view is needed,

@param $offset
   If $use_pager == false, skip the first $offset results. Does not work with pager. without paging on.

@param $filters
   An array of exposed filter ops and values to use with the exposed filter system
   Array has the form:
     [0] => array('op' => 'foo', 'filter' => 'bar'),
     [1] => array('filter' => 'zoo'), // for a locked operator, e.g.*   If no array is passed in, views will look in the $_GET array for potential filters

Comments

My own embedded views

I created the view and tested them to ensure I got the right results, including all fields.

The view in this example is named "myCustomView", created through the view interface.

Then, in my page, I inserted the following, including the php tags:

<?php
   
// show the custom view
   
$view = views_get_view('myCustomView');
    print
views_build_view('page', $view, array(), false, false);
?>

I don't know what all the arguments mean. Maybe this is enough to get you started.

Dave_From_Texas

Dave
(IRC nick: Davea1)
www.ingraftedsoftware.com

example with filter parameter

I have tried this and it works perfectly.

Of course, it brings back the entire set of the list specified in the view.

What I would really like to see an example of (something I haven't been able to manage yet) is the use of views_build_view which returns a subset of the list based on a filter.

For example, suppose I have created a view that has an exposed filter based on a cck added integer field, which is greater than. For example, a cck created node which 'company' with the added integer field 'number of employees'. Or a picture gallery node with number of hits, or votes.

How do I specify the equivalent of an interactive exposed filter value using the views_build_view() function?
Any help here would be spectacular, and would be a big push for views itself.

Victor Kane
http://awebfactory.com.ar

With the third argument you

With the third argument you can pass parameters (an array of parameters). To pass 1 argument with the value 3:

<?php
$view
= views_get_view(10);
if (!
$view) { // Just in case your view with ID 10 does not exist anymore....
   
drupal_not_found();
    exit;
  }
$content = views_build_view('embed', $view, array(0 => 3), $view->use_pager, $view->nodes_per_block);
print
$content;
?>

So my guess is that to pass a filter value, you need to pass it as an argument to your view (not 100% sure about this).

Tech. articles with a WAMP+IIS+Drupal focus

thanks! I was looking for

thanks! I was looking for something similar, but instead of args I used filter:

$view->filter[0][value] = "3";
print views_build_view('embed', $view, $view->args, $view->use_pager, $view->nodes_per_block);

dynamic views filter in a block?

Can you explain how you got the above code to work? Does it also work in a block?

I'm trying to display a context sensitive view by setting its filter according to which page (nid) is being viewed. I have the view embedded in my template page (page.tpl.php) and wish to set this views filter dynamically. Here's what I have (which does not work).

$myview = views_get_view('page_quotes');
$myview_args = array();
$myview->filter[3][value] = "frontpage";
print views_build_view('block', $myview, $myview_args, false, 4);
}

dynamic views filter

Here's something useful that may save a day of searching...

This can be used to embed a view in a template page and pass variables to a view argument. One can use this to display a view in relation to the node id or whatever desired context. One may use this method to create a generic view and pass variables to the view argument in order to output content related to context.

A simple example where this can be used: To display related random quotes on different areas of a site. Lets say you have a cck (content) type called quotes. One of the of the cck fields is a list type text field where a user, when creating a quote node, selects from the list which area of the site the quote should appear on.

A view can be created with filters set for this content type and an argument can be added related to the cck field. The view can then be embedded into a template page and the view argument can be dynamically set. I used this instead of having to create 12 different views for different areas of the site. Taxonomy was not an option so cck was used instead. Here's an example...

<?php
// you may use an if else statement to set the variable
// to be passed to the view argument based on nid
if ($is_front) {
$viewarg = 'your_variable';
} elseif (
$node->nid = '20') {
$viewarg = 'your_variable2';
} else {
$viewarg = "your_default_variable";
}
// you may call the view using its id or name:
// views_get_view("your_view_name")
$myview = views_get_view(2);
//set the view argument $args[0] to your_variable before building the view
$myview_args = array(0 => $viewarg);
// instead of block you may use page or embed
// block and page will display the view according to the
// your block and page options set when creating the view
// 4 sets the number of nodes to display
// false sets the pager to false
print views_build_view('block', $myview, $myview_args, false, 4);
}
?>

Further reading....
Inserting views into a template page: http://drupal.org/node/48816
Defining and passing views: http://drupal.org/node/129532
How to insert multiple views in a node: http://drupal.org/node/85720
Context sensitive embedded views: http://drupal.org/node/124446

keywords: dynamically filter view, pass arguments to embedded view

Pass-in URL, otherwise problems!

If you have any Exposed filters on the embedded View, you need to pass-in a correct URL, otherwise the Submit button on the filters will break (i.e. point only just to the View, so after clicking the button you'll get it NOT embedded inside your original page).

The correct way is for example like this:

<?php
$view
= views_get_view('myCustomView');
$view->url = 'node/$arg';
print
views_build_view('page', $view, array(0 => 3), false, false);
?>

The value for $view->url is worth a little discussion. Basically it's just the URL to your page (for example 'node/###'), where the Submit should be directed again, to have the resulting view embedded exactly where the original was.
The tricky part comes into play, if the third argument to views_build_view() is used for filtering: In this case, Views are re-encoding its value into the URL, which is rather strange in this case, and currently (Views 5.x-1.6-beta5) results in these limitations:
--- You cannot pass url-alias
--- The arguments must be present in the URL
--- The arguments must be replaced by the Views' typical placeholder '$arg'

So this is why I didn't use 'my_url_alias' nor 'node/###', both these will get another '/###' appended by Views. The final url after submitting the filters in my example will be 'node/###&filters......', where ### is the number 3 taken from the array.

Drupal 6 Views missing views_build_view() at present.

This will most likely be resolved once the views module is completed.
Work around:

<?php
function views_build_view($view_name, $args = array()) {
 
$view = views_get_view($view_name);
 
$view->set_arguments($args);
 
$view->execute();
  return
$view->result;
}
?>

Hope this helps someone.

In Views 2 / Drupal 6 you

In Views 2 / Drupal 6 you can use views_embed_view() in place of views_build_view().

Doesn't take all the same arguments. It works like this:

<?php
print views_embed_view($viewname, $display_id = 'default');
?>

Of course you can supply different $display_id's, but default is a good option since it'll always be available, and not all views may implement a block or page display.

$viewname is just a string representing the name of the view.

mlsamuelson

mlsamuelson

Two different page of one view

I used :

<?php
   
print views_embed_view('biblio_comments', $display_id = 'Textual');
print
t("<hr>");
        print
views_embed_view('biblio_comments', $display_id = 'Chart');
?>

But it shows the default page twice.
biblio_comments is a view which has two page. the second page (Chart) overrides the default display style values.

How do I pass an argument with this?

My view is taking the node $id to filter what it shows - I want to use views_embed_view in node.tpl.php (teaser state) so that it embeds beside every node's teaser. I'm getting it to embed great, but I can't pass the argument. I tried:

<?php
   
print views_embed_view('article_list_comments_recent',$display_id='default',$id);

;
?>

and
<?php
   
print views_embed_view('article_list_comments_recent',$display_id='default',$teaser_id=$id);

;
?>

and
<?php
       
@param $teaser_id;
    print
views_embed_view('article_list_comments_recent',$display_id='default',$teaser_id=$id);

;
?>

Obviously not educated in PHP here. ;)
Thanks!

Never mind - found it!

Seems like it's a thing with Drupal that the minute you give up and ask, you find it two seconds later. ;)

Thanks to this post by paulwamail:
http://drupal.org/node/373628

It seems you just pass an array as the third paramenter, making sure it has the values you need.
(plus, I needed to use $node->nid, not $id).

<?php
    $current_view
->args[0]=$node->nid;
    print
views_embed_view('article_list_comments_recent',$display_id='default',    $current_view->args);
?>

args[0]

we had to do pass $current_view->args[0] for a view with only one argument, like this:

print views_embed_view($view_name, "default", $current_view->args[0] );

Exposed Filters

Here's an example using Exposed Filters (Views 1 on Drupal 5) - the documentation above has a bug in it. Instead of the array being:

[1] => array('value' => 'zoo'),

It should be

[1] => array('filter' => 'zoo'),

So, as a complete example:

$filters = array(
    0 => array('filter' => 'foo'),      
    1 => array('filter' => 'bar'), 
    2 => array('filter' => 'zoo'), 
  );

  $view = views_get_view('name_of_your_view');
  $items = views_build_view('items', $view, null, false, 0, 0, 0, $filters);

----- Check out the Florida Drupal Users Group
----- http://groups.drupal.org/florida

Thanks

Updated the documentation to reflect this.

------
Personal: Outlandish Josh
Professional: Chapter Three

------
Personal: Outlandish Josh
Professional: Chapter Three

$view->filter[]= VS. $view->filter['something']=

In Drupal 5 with views, if you are adding your own filters like

<?php
$view
= views_get_view('something');

//below structure based on print_r($view), when view created via GUI
$view->filter['']=array(
'vid'=>$view->vid,
'tablename' =>    NULL,
'field' => 'node_data_field_something.field_something_value_default',
'value' => array($value2->node_data_field_something_field_something_value),
'operator' => 'AND',
'options' => NULL,
'position' => 1,
'id'=>'node_data_field_something.field_something_value_default',
);

$output = views_build_view('page', $view, array(), false, false);
?>

You might find strange things (multiple views with different filters hides certain views) happen. In that case, try using a named array key, so instead of

<?php
$view
->filter[]=array...
?>

try

<?php

$view
->filter['something']=array...
?>

this worked great for me!

Drupal 6 equivalent of views_build_view

Here is the equivalent of views_build_view for Drupal 6.

    $view = views_get_view($view_name);
    if (!empty($view)) {
        $output = $view->execute_display($display_id, $view_args),
    }

Some notes:
$view_name is the main name of your view which you see under menu item Site Building -> Views -> List
$display_id is one of the displays that you've set up for that view. Get the display id using the display name and selecting it from the views_display tabe.
$view_arg must be an array of the arguments for the view.

Not sure why I can't seem to get this to work...

I looked in the table (phpMyAdmin) at the views_display field and it it looks like the id = "page_1", or should I use the vid field for $display_id? I don't have any args (yet) for this one... just trying to get the view to display at this point.

Any help would be great!

$view_name = 'members_events'; //name of view
$display_id = 'page_1';
$view_args = array();
    $view = views_get_view($view_name);
   
   
    if (!empty($view)) {
   
        $output = $view->execute_display($display_id, $view_args);
    }

UPDATE - Figured it out my error... sorry folks...

Here is the example

Here is the example of display_id

    $view = views_get_view($view_name);
    if (!empty($view)) {
        $output = $view->execute_display("Defaults", array());
    }

No woman no cry

I am able to get the view to display on the page using the execute_display() function, but no matter what I give it for the display_id, it always just shows the default display. I looked in the views_display table and the id=block_1 and the display_title=Block. I have tried $view->execute_display('block_1', $view_args); and $view->execute_display('Block', $view_args); but it always displays the default. Any ideas why?

A little more info. I am using this inside of my theme_taxonomy_term_page function which I have overwritten in my theme in the template.php file. For most vocabularies I want the standard display, but for one particular one I need to use my view.

Thanks for your help.

views_get_view never empty

My views_get_view html-output is never empty, so the condition
if (!empty($view)) {[...]} never works for me. The html-output has at least an empty div-container. I use Drupal 6.10/Views 2.4. Has anybody else the same problem or a solution? A workaround would be great too.

anyone?

how can we test if the $view has data?

when calling views_get_view I

when calling views_get_view I just test with

$view = views_get_view('viewname');
if ($view) {
    ...
}

that works for me (D5).

taxonomy/term views

well... after some strugling to create my dynamic blocks with views ( where they cant pass argument ) I did some stuff for me... Mind that I I am not a programmer but that solved my problem...

1. Created a view with taxonomy TERM ID is the argument and
Display all values for sidewide visibility or
Use empty text for only related terms of nodes durin taxonomy

2. Then wrote a function for general use to be called from page, node, or php block snippets and put it into template.php

<?php
function mytheme_blockview($myview, $mylimit, $mytype) {
// $myview is the view name
// $mylimit is the number of items
// $mytype can be block, page or embed

// GET_TERM_ID_FORVIEWS
$termcheck = strstr($_GET['q'], 'term/');
$termID = str_replace('term/','', $termcheck);

if (
is_numeric($termID)) {

$view_name = $myview; //name of view
$view = views_get_view($view_name);

    if (
$view) {

   
//GETVIEW
   
$limit = $mylimit; // number of returns
   
$type = $mytype; // number of returns

   
$view_args = array($termID);
   
// PRINTVIEW

     
$output = '<div id="smart_blockview_'. $view_name .'">';

   
$output .= views_build_view($type, $view, $view_args, FALSE, $limit);
   
$output .= "</div>\n";

    return
$output;
     }
/* end if view */

} /* end if is_numeric */

}
?>

3. Finally called the function whereever I want with variables can be changed for each call

<?php
echo mytheme_blockview(myview, 3, block);
?>

needs tobe be checked for multiple vocabularies thou
Thats it... :) I hope somebody finds that useful ... Cheers

About this page

Drupal version
Drupal 4.7.x, Drupal 5.x

Archive

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.
nobody click here