Drupal: Calling Views In Code

Drupal is a fairly flexible system as far as CMS applications go, and is even more flexible as a development platform. The Views module gives developers ways to dynamically build queries of data, and display that data in many different ways. Sometimes, however, you want to display views in ways not supported through the admin interface. Fortunately, there are other ways to get the job done.

For example, I have a block in my sidebar where I want to display a list of the latest blog post, latest forum topic, and latest user poll. Each of these lists can be created as separate views. However, there doesn't seem to be any functionality, either in the Views module or another third-party module, that allows you to display multiple unrelated views in a single block. So, we turn to the code. The Views API provides a mechanism for building and displaying your views anywhere in your templates:


<?php views_get_view($name_of_view); ?>

and

<?php views_build_view($type$view$view_args$use_pager$node_limit); ?>

Clearly, the views_get_view() function retrieves the view definition from the database, while the views_build_view() function renders it.

Back to my example - I simply created a new block, and set the input format to PHP. Then, I used the following code to populate the block with the views:

<?php
<h2>Latest Blog Post:</h2>
<?
php  echo views_build_view('embed'views_get_view('latest_blogpost'), nullfalse1); ?>
<h2>Latest Forum Topic:</h2>
<?php echo views_build_view('embed'views_get_view('latest_forumtopic'), nullfalse1); ?>
<h2>Latest Poll:</h2>
<?php echo views_build_view('embed'views_get_view('latest_userpoll'), nullfalse1); ?>

The above code shows the rendered view. However, there are times where you want or need to do some additional processing on the values returned by the view. Fortunately, the Views module is incredibly powerful, and has a ton of options for retrieving the views.

In the above example, the first argument to the views_build_view() function is 'embed'. There are several other options:

  • page - Produces output as a page, sent through the theme. The only real difference between this and block is that a page uses drupal_set_title to change the page title.
  • block - Produces output as a block, sent through the 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 - Returns an array of information, including a database object that you can use db_fetch_object() on
  • items - Returns an array like resul, however, it contains an array of objects found by the queries, so you don't have to fetch the objects yourself.
  • queries - returns an array, summarizing the queries, but does not run them

This information comes directly from the code, and hopefully, it will be of some assistance to people who are looking for this kind of functionality.

[tags]block, cms, development, drupal, php, templates, Views[/tags]

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

nike store outlet

thank you for your post

tattoos for girls

Certain zones of the figure can just suit minor tattoos, for example the wrist, lower leg and foot. We at igotinked.com are always there to help to know where your tattoo suits you best.

sac lancel

en cuir à base est encouragée par les gammes de prêt-à-porter de sac lancel ainsi fournit une bonne espiègle en plus de Lancel Sac étincelants variété bourré de féminité. Sacs conjointement avec modules conçus en cuir de veau associé à certains pays en développement un colorant quelques pauvres ajouter une autre qualité autour de la matière monogramme standard. Lancel style de la marque robuste et design, gratuit, ainsi que simple et indépendante des femmes au moment de l'aplomb du temps, soulignant l'élégance particulière douce. vente privée sac a continué destiné à la conception féminine de la magnificence de créer manière, tout en maintenant à exprimer dans l'introduction de l'intérêt de conception récente vogue dans les coutumes et l’athlétisme, sacs à main lancel représente la nouvelle façon de durée de vie. Lancel 2012 démontrent nullement Hiver La mode n'est pas une exposition de grande envergure pour l'autorisation expresse de la mode, remplacée par une exposition peu plus simplifié. Le spectacle d'atteindre avec précision les 30 catégories de vêtements tous ensemble celui-ci sont habituellement soigneusement sélectionnés dans collection lancel chaque ensemble a tendance détails exclusifs et site attrayant. Alors que vous pouvez acquérir un nom de marque distincte mais en raison de l'exécution, vous ne pouvez pas obtenir ce que, suite à ces sortes de sosie portefeuille lancel peuvent répondre à la souhaitez. Un individu d'identifier un nom de marque et vous pouvez peut-être absolument l'obtenir. Ainsi, ce serait exactement le sac brigitte bardot choisir; Posséder les à l'intérieur de la même manière créées, sacs haut de gamme avec des taux exceptionnels. C'est bourses disponibles à cette entreprise approche aussi viennent dans différents styles, de conceptions et de types, et vous ne sera sûrement en trouver un qui convient à vos besoins et la conception exige. Il ya aussi le matériel en cuir construit de bonnes bourses créés en plus de prise à commencer par tous les différents $ 75. Toute la collection de pochettes couleur fantastique Lancel est peut-être un élément que toutes les femmes peuvent souhaiter. De l'indigo coloration glamour pour les séduisantes blanc brillant pour ne pas mentionner élégantes couleurs grises; demander sac a main lancel dames tout ce que vous préférez.
http://www.itbag-lancel.com/

jcfcgu fya5

ErwnNKLS ooolGLVyk wzkzqdvuoq ZEYaYpsna qselyz PmpUFFXVzav HavwSFVJ dydiKKQcy RqloVWPF obmiNXEsv

uskmpu cet6

BwluEZTI vtxqGDBra evixslkqey VRUxHducd ihzwgk WkvNEOVDfyk LrloWPUP ouoiIQAal JldqULZC kfufYBPhr

himfyn gxo4

HwipFFUF ltclSPOih xtrzbuewej QZKuQzzbx xobobu CvtPYVAKtew UzxgJCVI aydpMQNbf OuhbYZFY sdfwBGTwd

Michael Kors

Thanks for sharing! The fashion Michael Kors UK has constantly been evolving making many brand Michael Kors HandBags more challenging to maintain up with all of the newest Discount Michael Kors styles. As we all know, well-known brand are always popular around the world. And owning a luxury Michael Kors Hamilton seems to be a dream for all the women.
When it comes to 2012 new style Longchamp Bags, somebody would choose get online and find out some latest Longchamp Le Pliage Handbags. There are undoubtedly one of Hollywood's most favoured Discount Longchamp designers. The unique design Longchamp Hobo Bags attacted numerous of girls.

Note: I've found that when

Note:
I've found that when using the 'embed' option, it appears to use $view->page_type (That's the dropdown select under Page, View Type when editing the view) to determine what view type to use (teaser, full nodes, list, table, etc.), even if you have not checked "Provide Page View" in the views admin console ($view->page = FALSE).

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

About Erich

Erich is a web developer and a native New Englander who is passionate about life, the universe, and everything.

He is a Drupal consultant, previously employed as a senior developer at Harvard University, working on the IQSS OpenScholar project.  Prior to joining the team at Harvard, he was the engineering manager at CommonPlaces e-Solutions, in Hampstead, NH, contributing as the lead engineer on the Greenopolis.com and Twolia.com.

Erich is active in the Drupal community, having contributed modules and patches to the community. He presented at DrupalCon in Szeged Hungary, and co-presented at DrupalCon 2009 in Washington, DC.

Erich lives in New Hampshire with his wife, two sons, and three weimaraners.  When not writing code, Erich enjoys landscaping and woodworking.

Faceted search

Categories

Content type

Project types

Artwork Type

Artwork Tags

Recent comments

Activity Stream

August 29, 2011

August 25, 2011

August 24, 2011

August 23, 2011

August 15, 2011

August 11, 2011

August 10, 2011

August 9, 2011

August 4, 2011

August 3, 2011