Embedding a View in Drupal 6 using views_embed_view

Avatar-eric-london
Created by Eric.London on 2008-10-20
Tags:
New Comment
 
Please note: the content on this page orginates from ericlondon.com.
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));
?>


Comments

 
  • More Information
    Created by Eric.London on 2008-11-07
    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;    
    }
    ?>
    • seting the items per page to a view
      Created by Anonymous on 2009-03-17
      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
      • pager
        Created by Eric.London on 2009-03-19
        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
        • correction...
          Created by Eric.London on 2009-03-19
          $view->display_handler->set_option('items_per_page', 20);
          print $view->preview();
          • Where can i place the above
            Created by Anonymous on 2009-04-28
            Where can i place the above sniped to actually work
            • options
              Created by Eric.London on 2009-04-29
              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.
              • How to export a view and use it in your theme
                Created by Anonymous on 2010-12-06
                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
              • terms as args
                Created by Anonymous on 2011-05-10
                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
          • You'll need to do
            Created by Anonymous on 2009-04-29
            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
            • thanks
              Created by Eric.London on 2009-04-29
              nice catch, thanks!
              • php code (snippet) as input in body of content type
                Created by Anonymous on 2010-12-13
                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
                  Created by Anonymous on 2011-09-18
                  See this issue http://drupal.org/node/928882
            • omg i think I love
              Created by Anonymous on 2009-07-09
              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
            • php code (snippet) as input in body of content type
              Created by Anonymous on 2010-12-13
              This was very helpful - how would you load the jquery library so that it doesn't do a page refresh for the pager?
          • One thing I just learned about $view->preview()
            Created by Anonymous on 2010-03-11
            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
      • And this ?
        Created by Anonymous on 2010-08-04
        <?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();
        ?>


        :)
    • Thanks for this tip!
      Created by Anonymous on 2009-03-23
      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.
    • How to hide the title when the result is empty?
      Created by Anonymous on 2009-08-20
      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
      • jQuery hover html
        Created by Eric.London on 2009-08-20
        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
          Created by Anonymous on 2010-01-19
          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.
      • Here you go
        Created by Anonymous on 2010-01-19
        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.
    • So if I want to access view information...
      Created by Anonymous on 2009-11-09
      <?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
    • Hide if empty
      Created by Anonymous on 2011-09-22
      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?
  • Thanks! This was exactly
    Created by Anonymous on 2009-04-23
    Thanks! This was exactly what I was needing.
  • Need help embedding a view and preserving the table formatting
    Created by Anonymous on 2009-05-01
    <?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?
    • hmm
      Created by Eric.London on 2009-05-04
      Can you send a screen shot?
  • How to print only 1 element of the output
    Created by Anonymous on 2009-08-24
    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?
    • view theming
      Created by Eric.London on 2009-08-30
      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
        Created by Anonymous on 2009-10-16
        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?
  • Embedding a View with Dynamic Parameters
    Created by John Carbone on 2009-10-03
    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

    <?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 : )
  • The $view object
    Created by Anonymous on 2009-10-15
    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
            )
    
    )
    
    • views_get_view()
      Created by Eric.London on 2009-10-15
      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()
        Created by Anonymous on 2009-10-15
        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
  • This is just great!!
    Created by Anonymous on 2009-10-27
    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..
  • question about views_embed_view
    Created by Anonymous on 2010-01-25
    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?
    • hooks
      Created by Eric.London on 2010-08-13
      Views has some great hooks for modifying views objects: http://views2.logrus.com/doc/html/index.html
  • show view on a view page???
    Created by Anonymous on 2010-02-08
    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
  • Changing Default settings before embedding view
    Created by Anonymous on 2010-02-27
    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);
    ?>
    
  • Thank you for posting this
    Created by Anonymous on 2010-03-22
    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.
  • Thanks!...Eric
    Created by Anonymous on 2010-08-10
    This article proved get time-saviour when i was in very urgent need for such helper function.Thanks for writing it so consice.
  • One search and here is the solution
    Created by Anonymous on 2010-11-17
    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.

  • Congrats
    Created by Anonymous on 2010-11-18
    the info helped to solve an issue I had.

    tkx man
    Wils
  • embed view with filter
    Created by Anonymous on 2010-12-07
    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
      Created by Anonymous on 2011-01-12
      Instead of:
      print_r($view->result);

      try:
      print($view->preview);

      This should return the parsed HTML, which I think is what you want?
  • Cascading Views Output in default arguments
    Created by Anonymous on 2010-12-30
    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
      Created by Anonymous on 2011-04-28
      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.

  • When you use this method,
    Created by Anonymous on 2011-01-25
    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.
  • Great advise, many thanks for
    Created by Anonymous on 2011-05-10
    Great advise, many thanks for help will try with views 3