background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Embedding a View in Drupal 6 using views_embed_view

Eric.London's picture

Today I tried to embed the HTML from a View in a page layout following this guide. Apparently, in Drupal 6 the views_build_view function has been replaced by views_embed_view. Here's a code snippet that lets you to embed a view:

<?php
$viewName
= 'MYVIEWNAME';
print
views_embed_view($viewName);
?>

The views_embed_view has 2 default arguments. The second argument allows you to enter the display_id of the view (example: default, page, block, etc). Any additional argument you specify will be passed to the views argument handler. For instance, if you wanted to embed the block view and pass it a list of arguments...

<?php
$viewName
= 'MYVIEWNAME';
$display_id = 'block';
$myArgs = array(1, 2, 3);
print
views_embed_view($viewName, $display_id, $myArgs);
?>

Or, to implode numerous values into a single argument:

<?php
$viewName
= 'MYVIEWNAME';
$display_id = 'block';
$myNodes = array(1, 2, 3);
print
views_embed_view($viewName, $display_id, implode('+', $myNodes));
?>

Great advise, many thanks for

Great advise, many thanks for help will try with views 3

When you use this method,

When you use this method, does it apply content filters (the ones from /admin/settings/filters, not the view filters) to the teaser field for you? It seems to ignore the filters for me, while in Views preview it works fine.

Cascading Views Output in default arguments

I have view with the following composition:
1. default
2. page

What I need is to pass the output of default as default argument of page. How would be possible by php and hence need some direction or hints. Uptill now I have been to come up with the following code which is partially solving my problem:

<?php
$view
= 'sectname';
$view = views_get_view($view);
$view->execute();
$arg = $view->render_field('field_sectcode_value', 0);
return
$arg;
?>

This gives my the required argument string from the default but the page does not run may be due to the execute command. Please confirm what would be workaround so that I can execute the main view and not the view that is being use to generate the default arguments.

pull view for specific title

I have a content type that for each node within will have a specific view, is it possible to pull just the view for each node based on title? adding the node id or any other variable makes the use of drupal seem rather pointless, as the manual task over takes the automated reasons for using drupal.

I can create the views with the exact same name as the node machine name is my reasoning.

embed view with filter

Hi

Thanks for your helpful blog!
How can I embed a view with a filter applied?

I tried this code:

$view = views_get_view('Treffpunkt');
$display_id = 'default';
$view->set_display($display_id);
$filter = $view->get_item($display_id, 'filter', 'field_eventdate');
$filter['value'] = '2011-01-01';
$view->set_item($display_id, 'filter', 'field_eventdate', $filter);
$view->set_items_per_page(3);
$view->render();
print_r($view->result);

But I get this output:

Array ( [0] => stdClass Object ( [nid] => 1396 ) [1] => stdClass Object ( [nid] => 1762 ) [2] => stdClass Object ( [nid] => 119 ) )

Any clue what I am missing?

Instead

Instead of:
print_r($view->result);

try:
print($view->preview);

This should return the parsed HTML, which I think is what you want?

Congrats

the info helped to solve an issue I had.

tkx man
Wils

One search and here is the solution

Thx, eric,

not the first time i am visiting your homepage as i was redirected by that search engine. your article hit it in the black.

Thanks!...Eric

This article proved get time-saviour when i was in very urgent need for such helper function.Thanks for writing it so consice.

Thank you for posting this

It saved me a lot of work. (PS: This site is one of the best sources of good information on drupal configuration anywhere on the web.) Regards.

Changing Default settings before embedding view

How do i changed the default setting of "Items to Display" before embedding the view?

this is my current code:

<?php
print views_embed_view($my_view_name);
?>

show view on a view page???

Hey i found this article and i thing this is just what i need but don't really know how to implement this.

I have two views Products_overview and Product_news

the products_overview view is the default view used which displays a list of products. after a product has been selected all content types related to that product are being displayed using arguments. the product type Product news is also there but what i would want is to display by Product news View under the list of content types related to the product so the product news related to the selected product will be displayed. I think this can be done with the view embed function.

any help would be awesome

question about views_embed_view

hi, im new to drupal, and your site is a great resource for me! thanks :)

i have noted(if im correct) that when views_embed_view returns all the content from the view, my quest is how can i manage the different variables to display it as i want(and not all the content at once), or i have to call another function?

Eric.London's picture

hooks

Views has some great hooks for modifying views objects: http://views2.logrus.com/doc/html/index.html

This is just great!!

Thanx a lot! Is it possible to pass arguments as well? I have 1 main view - 1 page, filtering using arguments for taxonomy term location (usa, japan, brazil etc..), and want to embed another view using the same arguments.. so both of the views will be filtered using the same argument in URL, thanx a lot again, saved a lot of time..

The $view object

Hello Eric! Do you know how to get data from Views 2 ?

I use $view = views_get_view('view_name');
Then print_r($view);
+ I wrote it in page.tpl.php
But there is no data here! Only something like that http://www.flickr.com/photos/kentbye/511817875/sizes/o/

I want to get something like that http://drupal.org/handbook/modules/views/api#comment-247361

Can I get this (array below) using the "views_get_view" function ?

Array
(
    [0] => Array
        (
            [field1] => foo
            [field2] => foo
        )

    [1] => Array
        (
            [field1] => foo
            [field2] => foo
        )

)

Eric.London's picture

views_get_view()

You might want to try using views_get_view()...

<?php
$view
= views_get_view($viewName);

echo
"<pre>" . print_r($view->result, true) . "</pre>";
// krumo($view);
?>

views_get_view()

By the way, you have empty array $view->result too

views_get_view()

Yeah. I tried this

<?php
$viewName
= "bro";
$view = views_get_view($viewName);
echo
"<pre>" . print_r($view, true) . "</pre>";
?>

but my output is

view Object
(
    [db_table] => views_view
...
    [result] => Array
        (
        )
...
    [vid] => 1
    [name] => bro
...
)

So $view->result is empty array!

Maybe function views_get_view() do not contain information like that ...
Maybe it is only about view's settings but not gained data from nodes

Embedding a View with Dynamic Parameters

Hey Eric, just wondering what your thoughts were on this one. I recently needed to add a view with dynamic parameters, based on nodereferences from another content type. For example, say I had an organization content type and a news content type that used noderef to tag the organization who's news it was. Nothing is really needed to display the organization on the news content type since noderef handles that, but what about displaying all the news items for that organization on the organization's page? I futzed a bit with using your embedded views example but in the end I took a different approach. I set up a block view, since I had a view of all news items already. Then I just added a "Content" filter of "is one of" (my noderef content type). Then I added the following to my template.php

function MYTHEME_preprocess_node(&$variables) {

    if ($variables['type'] == 'MY_ORGANIZATION'){
    _MYTHEME_preprocess_node_MY_ORGANIZATION(&$variables);
    }
}

function _MYTHEME_preprocess_node_MY_ORGANIZATION(&$variables){

    //grab the current nid
    $nid = $variables['nid'];
    //load the view
    $view = views_get_view('MY_NEWS_VIEW');
    //set the display. could have used 'default'
    $display_id = 'block_1';
    $view->set_display($display_id);
    //get the current setting of the filter
    $item = $view->get_item($display_id, 'filter', 'field_MY_ORGANIZATION_nid');
    //delete anything in the variable
    $item['value'] = NULL;
    //set the new variable by the current node id
    $item['value'][$nid] = $nid;
    $view->set_item($display_id, 'filter', 'field_MY_ORGANIZATION_nid', $item);
    $view->is_cacheable = FALSE;
    //render the new view
    $news = $view->render();

    //print it inside our formatted html and pass it to 'content'
    if($view->result){
    $variables['content'] .= '<div class="field-label-custom"><h2>News & Publications</h2></div>' . $news ;
    }
}

Just wondering what your thoughts are on this approach. Is it bad form to put this in a template file? Is rendering a block view here a bad idea since it's not actually in a block? And... is my code lousy in general? As you know, I haven't really be coding very long : )

How to print only 1 element of the output

I got this post after so much digging. I know this is what I need to do.

I have set up a content type to add client logos. In a particular node's particular area, I want to print the latest 3 logos. I am able to create a view as well as print the output of "views_embed_view" like you have mentioned. But, now I want to apply CSS styles to each of the result elements. I tried the 'Title' method that you have explained. But for me the images are still getting out put together. Is there a way I can use a foreach or something? How can I get to know each of the output array elements?

Eric.London's picture

view theming

If you are trying to show the latest 3 logos, I would edit the view settings and change the default sort order to "Node published" (sorted descending), and limit the number of results to 3.

In regards to theming the output of your view, go to your view edit screen (admin/build/views/edit/VIEWNAME), and check out the section called "Theme: Information" under Basic Settings. If you'd like a custom layout for the output, you could change the view style to "unformatted", create a theme template file called "views-view-fields--VIEWNAME.tpl.php", and alter the html and css in this file.

hope this helps!
Eric

Theming embedded view

Are you sure, theming an embedded view works like that? If I open my view page theming with the template file works but when I create a node with a views_embed_view php snippet the theming is not applied. Any idea?

Need help embedding a view and preserving the table formatting

<?php
$viewName
= 'MYVIEWNAME';
$display_id = 'block';
$myNodes = array(1, 2, 3);
print
views_embed_view($viewName, $display_id, $myNodes);
?>

This snippet works, but it doesn't preserve the table formatting of the block view. How can I accomplish that?

Eric.London's picture

hmm

Can you send a screen shot?

Thanks! This was exactly

Thanks! This was exactly what I was needing.

Eric.London's picture

More Information

views_embed_view does not show the view's title. Here's how you can get the title from the view object:

<?php
$viewName
= 'MYVIEW';
$viewHtml = views_embed_view($viewName);
if (
$viewHtml)
{
   
// load view object
   
$view = views_get_view($viewName);
       
   
$title = $view->display['default']->display_options['title'];

   
$page_contents .= "<h2>$title</h2>";
   
$page_contents .= $viewHtml;   
}
?>

Hide if empty

If I output directly "views_embed_view", My view hides if it is empty and if all views are empty, the block hides. If I use "if ($viewHtml)" as in the example above, the if statement is always true. In other words, The title is printed always. Should I use something else for the if statement?

So if I want to access view information...

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

 
// ensure view exists
 
if (!$view) print("Not real");

 
// set display_id
 
$view->set_display('block');

 
// execute view
 
$view->execute();
 
$viewArray = $view->result;
  echo(
"<pre>"); print_r ($viewArray); echo("</pre>");

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

But where does that leave custom content types?

$node->data->subtitle?

I dunno

How to hide the title when the result is empty?

Hello,

I tried your solution and it’s working great.

My view can display an empty result, so only the title is showing. I didn’t find how hide my title when the result of my view is empty

My view is always returning me a result even if there nothing to display

Could you help me?

Best regards

Here you go

Hey, found this at http://drupal.org/node/356324

This will show the view, with title, only if there are results.

Template.php

// Get view
$view = views_get_view('VIEWNAME');
$vars['view_title'] = $view->display['default']->display_options['title'];
if ($view) {
  $views_arg = $view->preview('block_1', array($fields['nid']->content));
  if (!empty($view->result)) {
    $vars['view_results'] = $views_arg;
  }
}

Then in your tpl.php:

if ($view_results){
  if ($view_title) {
    print '<h3>'.$view_title.'</h3>';
  }
  print $view_results;
}

- The guy next to you.

Eric.London's picture

jQuery hover html

My code was originally written for Drupal 5, when the hover links were not included in the result. You can either turn off the jQuery admin links, or update the conditional statement. Here is a more accurate way of testing if the view has results:

<?php
// create string variable for page content
$pageContents = "";

// set the view name
$viewName = 'test_view';

// fetch the view object
$view = views_get_view($viewName);

// get the title for the view, if there are results
if (is_object($view) && count($view->result)) {
 
$title = $view->display['default']->display_options['title'];
  if (
$title) $pageContents .= "<h2>$title</h2>";
}

// add view html to page contents
$pageContents .= views_embed_view($viewName);

return
$pageContents;
?>

Here you go

Hey, found this at http://drupal.org/node/356324

This will show the view, with title, only if there are results.

Template.php

// Get view
$view = views_get_view('VIEWNAME');
$vars['view_title'] = $view->display['default']->display_options['title'];
if ($view) {
  $views_arg = $view->preview('block_1', array($fields['nid']->content));
  if (!empty($view->result)) {
    $vars['view_results'] = $views_arg;
  }
}

Then in your tpl.php:

if ($view_results){
  if ($view_title) {
    print '<h3>'.$view_title.'</h3>';
  }
  print $view_results;
}

- The guy next to you.

Thanks for this tip!

I'm fairly new to Drupal, and I keep on finding cool things that make my life so much easier!

Sadly (as in this case), I usually find these tips after spending many hours struggling to do the same things with my own code.

seting the items per page to a view

How can we set the items per page to a view, programatically?

The simila code we are using in drupal 5 is as follows:
$view = views_get_view('visual_articles');
print (views_build_view('embed', $view, array(0 => '1', 6 => $key[1), $view->use_pager, $view->nodes_per_block));

Can u please give me the corresponding code in druapal 6
Thanks in advance.
Cibi
cibi.jacob@gmail.com

And this ?

<?php
$view
= views_get_view("visual_articles");
$view->set_items_per_page(24);
$view->set_use_pager(true);
$view->execute();
$node->articles_view = $view->render();
?>

:)

Eric.London's picture

pager

Hi Cibi,

I have not tried to do this yet with Drupal 6. You might want to try loading the views object and then setting this variable: $view->pager['items_per_page']

Hope that helps!
-Eric

Eric.London's picture

correction...

$view->display_handler->set_option('items_per_page', 20);
print $view->preview();

One thing I just learned about $view->preview()

If you have a feed display attached to the view, the display will get triggered and the feed icon will appear (even if you don't want it to).

You can get around this by setting $view->is_attachment = TRUE; before calling preview().
See: http://drupal.org/node/734096#comment-2703886

You'll need to do

You'll need to do a
$view->set_display($display_id);
before calling
$view->display_handler->set_option('items_per_page', 20);
otherwise you get a Fatal error: Call to a member function set_option() on a non-object

php code (snippet) as input in body of content type

This was very helpful - how would you load the jquery library so that it doesn't do a page refresh for the pager?

omg i think I love

omg i think I love you...
I've been looking for this on and off for weeks! weeks I tell you, and now, it works...
so beautiful I just might cry

Eric.London's picture

thanks

nice catch, thanks!

php code (snippet) as input in body of content type

Hi Eric...

Any idea on how to load ajax so the pager doesn't do a page refresh everytime?

Thanks much!

Sradox

See this issue

Where can i place the above

Where can i place the above sniped to actually work

Eric.London's picture

options

The easiest way to embed this is to create a node and choose PHP for the input filter. I prefer to create a module that contains a hook_menu() and page callback.

terms as args

Can you pls help me render first term on the node terms list as an argument here?

<?php $viewName = 'node_references_fields'; $display_id = 'default'; $myArgs = array(1, 2, 3); print views_embed_view($viewName, $display_id, $myArgs);?>

Works fine for me when i delete argument from views and it displays all arguments but i do need to have list of related by term materials, its my catalogue based on taxonomy. So need to have a block/field listing all other articles with the same tag

How to export a view and use it in your theme

I have a new Drupal theme I am working on and I would like to create the view export it and have a custom_block with the view once I enable the theme.

For example I have a view which lists all blog posts on the site and I want it to be in the block when I enable the module (the view will return the empty message if none are there of course)

I would most appreciate your advise - I see you have done some great things with views here.

Thanks