You are on page 1of 79

c  

 
  


2| Last modified: October 14, 2010

Views is primarily a tool for site builders who want to customize the presentation of lists of
content -- such as lists of articles, new content, and content controlled by taxonomy -- in ways
that are not built into Drupal.

Views creates these lists and can present them either as pages, blocks, or both. It can give these
pages menu entries, or create them as menu tabs. Views can provide output in a generic list, a
table, or lists of teasers (like the front page, where each entry links to the full article).

2| hy use Views? hy not write your own queries?


2| Definitions
2| Views Basic Options
2| ^age Views
2| Block Views
2| Inserting Views
2| Views Arguments
2| Views Fields
2| Views Filters
2| Views Sort Criteria
2| ºSS feeds for Views

 c  



 
 

  


2| Last modified: July 27, 2010

Ôhe decision to use the Views module over writing your own queries and presentation in a
custom module is a decision that every developer must make, and one that will be important to
the success of your project. Ôhis page raises some points to consider when making such a
decision.

£  
 

Daving custom code offers the following advantages:

2| £omplete control over the data fetched. Some SQL queries are difficult to replicate in Views.
2| Some opportunities for query optimization might exist when writing custom code. Views is as
efficient as a general tool can be, but the specific details of your target query might mean that
further optimization is possible.
2| £omplete control over presentation. You have the honor/privilege/duty/requirement of writing
all presentation details for your data.
2| £omplete knowledge of your code. If you write it yourself you know what it contains. £ompare
this to the task of studying the Views codebase.
2| ºevision control systems like £VS, SVN. If your view is stored in the database you risk losing it
when the db becomes corrupt. Note that you can export views to PHP code and put them in
custom modules, though, so this one equals out.

c   
 

Daving the Views module offers the following advantages:

2| £hange behavior without changing code. You can alter your application at runtime without
worrying about breaking code or making a PHP syntax error. (Note: since views that are stored
in the database do not have revision control, changes made like this cannot simply be undone...
be warned)
2| ·any options for presentation. Different view types mean that you can change the presentation
of the data you fetch.
2| Glack box. You don't need to write or read any PHP code to get started with Views.
2| Data safety. ·alicious users can do a lot of damage without proper data safety testing. Views
goes through the trouble to scrub all data it presents, so you can feel assured that as long as the
module providing the data properly implements the Views API, its data will be safe.
2| {pen architecture. If you are a developer, you can write to the Views API and add features,
presentation styles and behaviors to Views in custom modules. These are then reusable in other
views that you later create.
2| £ommunity benefit. You will be the recipient of an enormous amount of Views code that is
being contributed and improved by the community. There will be Views features available
tomorrow that weren't here today. There will be people fixing Views bugs while you sleep. This
won't be the case for your custom code.
2| ºeuse views. Guild a basic view that does something useful, export it, and then use it on the next
site you build.
2| Tight integration with ££ , Voting API, and many other modules that you might already be
using. Every contrib module can potentially extend Views, so make sure and take inventory of
what modules you plan to use when evaluating Views on its own.
2| Panels integration. Panels 2 is especially powerful and the Views integration is very good. Do
some research before you decide against Views.
2| Programmatic handling of views. You can instantiate views objects in PHP code and manipulate
them in many ways. The Views API provides several points of access to the views object, so if
you are really unhappy with what you can achieve with the Views UI, you can grab control of the
object itself.
2| Documentation. There is more documentation about Views than there is about your custom
code.
2| Page, menu and block integration. Views gives you page views and block views, and lets you
instantiate menu items as well.
2| Views 2 is more flexible than Views 1. ºesearch Views 2 before deciding against Views.
2| Exposed filters: Views gives you a lot of control over creating form elements to filter your view.
Writing FAPI code is bulky and verbose. Nothing against FAPI, but creating all those dropdown
selects, autocomplete text fields and checkboxes is a lot of work. You can still use formalter to
get to the exposed filters submission and validation handlers, so you don't lose any control by
going with Views here.

J  
  


2| Last modified: August 5, 2007

Views uses a lot of terminology to describe what it does, and while this terminology is generally
meaningful to anybody who has been around Drupal and databases for awhile, much of this
terminology is not inherently obvious.

c 
A view is some presentation of content; now, in real terms, it could mean a single piece
of content, or multiple. Views, however, is primarily concerned with    pieces of
content.
c 
A page view is a view that is ordinarily presented in the main content area, as the entire
page. Ôaxonomy views such as taxonomy/term and the Drupal front page are examples of
page views.
 c 
A block view is presented as a block, similar to the navigation bar. ºecent Updates and
^opular Content are good examples of block views.
  c 
Ôhe simplest type of View is the List View, which simply provides the content as an
Unordered List, i.e, the o  tag. Ordinarily, list views generally just display the title of
the post, but they can display a lot more than that. For example, a List View of recent
blog entries might look like this:

2| I had a great day yesterday


À  
 
2| ·y cat's antics
À   
2| hy I hate politics
ÿ 
 

On drupal.org, the 'New forum topics' could be a List View.

c 
Very similar to the list view, a table view provides information about the post in a one
post per row format. Columns can be click-sortable, meaning that the user can click the
header on the column and change how the view is sorted, though the site designer must
be careful as these sorting choices are easily overridden by the view itself.

c 
A teaser view displays the title of a post, plus the teaser, and links to the full view of a
post. Ôhe best example of a teaser view is to look at the front page of http://drupal.org
 
hen views refers to a field, it is talking about the field that is displayed in a view. For
example, the tracker view (which shows the user recently updated content in a table) lists
the type, title, author, number of comments and age. Each of these entries is a field.
Views only uses fields in List and Ôable views.

  
Views can take arguments from the UºL. For example, in the url
http://drupal.org/taxonomy/term/1 the number '1' is an argument to the view. It is used to
filter the view to be more specific.

  J 
hen a View expects arguments, and an argument is not provided, the argument default
describes the behavior of the View. Ôhere are essentially 3 types of behavior:

2| It can display 'page not found' meaning that the argument is absolutely required,
and if no argument is present it just 404s.
2| It can assume the argument was optional, and ignore it not being there. In that
case, it will simply display all values. For example, if the argument is supposed to
be a User ID, the view would only include posts by that user. Dowever, if the
argument isn't provided, and the Argument Default were set to 'all values', then it
would show posts from all users.
2| It can provide a Summary View. In this mode, it generates a list of all possible
arguments that have posts in the database, and provides a list that the user can
click on. Ôhis is used in the Archive-style view. For example, take a view whose
UºL is set to 'archive'. If the Views argument is set to "Year + ·onth", and the
default is set to "Summary View", calling 'archive' by itself would provide a list
of month/year combinations that have posts, along with a summary of how many
posts were found. Each of these would be a link to archive/CCYY·· which
could then show all posts from that month.

  

A filter is used to reduce the result set. For example, the very basic view with no settings
will simply give all content available on the site. Ôhis is almost never actually useful,
however! Instead, content is almost always filtered so that it provides only what is
needed. Ôhe default Drupal front page view, for example, filters to content that is set as

  
 , and additionally filters to content that is set    .
!    

An exposed filter is a filter that the end user is allowed to set. Ôhis means that Views will
provide a text box or a select box and the user can specify criteria. Ôhe most common use
for this is to filter by specific taxonomy terms, and let the user choose them, but there are
many other uses for this as well. Exposed filters only work on " .
#
$


Content needs to be sorted in some way in order to be useful. In general, Drupal likes to
sort content in descending (reverse) date order, meaning that content is presented 
. Ôhis is great for the front page, but sometimes date is not the most important
criteria. Often taxonomy pages should be sorted alphabetically, for example.
J  c 
Views and modules that utilize Views can provide default views; these views will
automatically appear on your system just by being installed. Ôhey can be enabled or
disabled. Ôhey can also be 'overridden' by a creating a view with the same name. Ôhe
easiest way to do this is to click 'add' next to the default view, modify the view as you
like, and save it.

c  % 


  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: December 7, 2007

Views has three basic options that every View must have.

 
Each view must have a    name. Ôhe name is used to identify the view to Drupal;
the name of a view can be important if your view is overriding a   " , and is also
used for  . Your name should not contain spaces or punctuation other than _.

You can control which roles have access to the view. Simply check which roles apply. If
no roles are checked,  roles will have access. ·ake sure to uncheck "access all views"
for anonymous (or other role) in the admin/user/access page, otherwise this won't work.
J
 
Ôhe description of the view will only be shown on the view administration page, and is
simply a reference to what the view actually does. You may put anything you like here.

c 
  


2| Last modified: September 17, 2007

A page view is one that is accessible via   meaning it can be linked to directly, and the view
appears in the main content area.

In order to provide a page view, the '^age View' setting must be checked; if unchecked, settings
in this section will be ignored.
Some items in this list will be marked as advanced features, and require some understanding of
Drupal to really 'get'. Don't worry if these descriptions don't make sense to you; feel free to
ignore them.

 
Ôhis is the Drupal UºL from which the view is accessible, and is set just like UºLs from
in the menu; do not include the leading or trailing slash, and do not include http:// or your
site's base UºL in it. For example, if your site is http://www.example.com and you want
your view to have the UºL http://www.example.com/archive, then you simply enter
'archive' in the UºL field.

Ôhe UºL supports an option to rearrange the UºL slightly and provide part of the UºL
as an argument. Ôhis is especially useful when views are created as tabs on the user
profile. For example, the UºL to a user's profile is user/UID -- if your drupal.org UID is
26979, then your profile will be located http://drupal.org/user/26979. If you have a view
to display recent posts by a user, and that provides a menu tab, and you want that tab to
appear on a user's profile page, the UºL would have to look like this:
http://drupal.org/user/26979/track -- in order to get this to work, you need to specify that
number as an argument. You could specify that argument as 
&'
&
. By using
$arg as a placeholder, Views will know that that section of the UºL is an argument and
will pass that through as the first argument to the View. See the section on Arguments for
more detail.

c 
Choose any of the types listed. (See the definitions page for more detail.) Ôhe type
chosen is applicable only to ^age Views; Block Views can have their own type.
 
Ôhis is the title of the View, as displayed on the page. Ôhe title can use % substitution to
include arguments in the view, if your view uses Arguments. (See the argument section
for more). You may use %1 for the first argument, and %2 for the second argument, etc.
For example, if you have a view which has 4 arguments: UID, Year, ·onth, Day and is
meant to display blog entries, you might use the following title: Blog entries for %1 on
%3 %4, %2 which would translate to G    ! 
!.


If your view might return a lot of entries, you can (and almost certainly should) check
this; it will use Drupal's built in paging system to return only the specified number of
entries per page.

 

      (  " #
Ôhe breadcrumb trail is the line that informs the user where in the system a given page is;
it is generally constructed from the menu tree or from taxonomy. Ôhis option will only
very rarely be checked; in fact, in general only for the 'front page' view will the trail 
include Dome, and generally because that page  Dome and doesn't need to link to itself.
  

Ôhis option tells Views how many results to return on the page. If the pager option is not
checked, then this is the maximum number of posts to display. You may enter 0 here for
no limit.

" )
If checked, Views will create a menu entry for this tree, so that it may appear in the
Navigation menu. Ôhe menu.module can be used to customize and/or rearrange this menu
item. If not checked, all items in the menu field set will be ignored.

" )  " #
If checked, the menu will be provided as a 'tab' rather than a normal menu item. Ôhis
means that instead of showing up in the navigation, it will show up as a menu tab, similar
to the 'view' and 'edit' options on a post. Ôhere are two important considerations here:
First, the UºL to the view needs to have at least two portions, meaning it must be in the
form of foo/bar (or foo/bar/baz) and can't simply be foo. Ôhis is because that the tab for
foo/bar will show up on the UºL foo. Ôhe second consideration is that tabs will only
appear if there are at least 2 of them to choose from.
)J  )  " #
hen creating a view (or more likely, multiple views) as a tab, you may need to set one
of them as the default tab. For example, if you have two views, foo/bar and foo/baz, and
you set foo/bar as the default menu tab, when you navigate to foo you will see the page
for foo/bar, and foo will contain a tab that lets you also go to foo/baz.
  " #
If a view is set to be a menu tab, this option specifies the 'weight' of the tab. Lower
numbers will appear more to the left. Ôhe default is 0, and if two tabs have the same
weight they will be sorted alphabetically.
)  
Ôhis is the name of the menu entry (or tab) that the View will have. It doesn't need to
match the main title, (and should not if using % substitution in the title). You may not use
% substitution in this title.
( 

Ôhe header will appear at the top of the view. It may be a short message describing the
view; it may also be, if you have the proper permissions, ^D^ code that can run a snippet.
 

Ôhe footer will appear at the bottom of the view. It may be a short message describing the
view; it may also be, if you have the proper permissions, ^D^ code that can run a snippet.
 !
Ôhe empty text will appear if the view returns no results. It may be a short message
describing the view; it may also be, if you have the proper permissions, ^D^ code that
can run a snippet. NOÔE: If the view returns no results, the  
and  
will not
appear! If you want the header/footer to appear when a view returns no results, you need
to duplicate it in the Empty Ôext!

(  $
   *# *   
+
( ,-./.!&0.!1
  

2| Drupal version: Drupal 4.7.x, Drupal 5.x
2| Last modified: ·arch 19, 2009

Description:
Ôhis DowÔo: provides basic instructions to display, through the Views module, one random
piece of full content from everything published in the last two weeks to show up on the front
page of your site every time someone loads the site's front page. (Anonymous users constrained
by site wide Cache settings.)

Additionally, as Views does not currently update the {node_counter} .totalcount or .daycount in
this instance, a (kludge) mechanism is provided to increment both fields for the single Full Node
that is being displayed. Unfortunately the kludge to update the totals does not work correctly for
anonymous users if your site has cache turned on. You will get one totals update per caching.
hen (If?) I find the mechanism to disable cache for a View, I'll update here with the
information.

Credits:
Ôhis page was created by the knowledge of mkalbere, coreyp_1, and dvessel. I just summarized
all the parts and did the write up. -· Ô

# # # ºandom Front ^age # # #

A) Create a New View

4.7.x Home  Administer  views : Add


( /admin/views/add )

5.x Home  Administer  Site building  Views: Add


( /admin/build/views/add )

B) Basic Information Block


- Add "Name:" and "Description:"
- nCheck all boxes in "Access:"

C) In the "Page" Block


- check the "Provide Page View" box
- in " :" enter a url
- in "View Type:" select "Full Nodes"
- uncheck " se Pager"
- check "Breadcrumb trail should not include "Home""
- set "Nodes per Page:" to 1

D) Filters Block (Add Filter)


- "Node: Published" "Equals" "Yes"
- "Node: Front Page" "Equals" "Yes"
- "Node: Created Time" "Is Greater Than" "now" "-1209600"

Optional [to include or exclude specific node type(s)]:


- "Node: Type" "Is None Of" "page" oo Select what works for your site
E) Sort Criteria Block (Add Criteria)
- "andom"

F) Click "Save"

# # # Update Counters # # #

Findings:
After exploring the var_dump($GLOBALS) given by Dvessel (
http://drupal.org/node/160921#comment-254323 ), there is seemingly no global var that holds
the displayed Node ID(s) accessible by ^D^ within a c . Both 4.7 and 5.1 have this same
problem and the below solution (ugly hack) works for both.

Constraints:
- Only tested for a View returning a single node in the ^age format.
- has less than stellar error handling (actually none).

Ôo find the NID(s):

A) hack views.module
- Add as the first two lines of "function theme_views_view_nodes("
ocode
global $whatisthenodeid;
$whatisthenodeid  $nodes;

Ôo update the counters:

B) create a View such as the one above , then:


 In your View's Page  Footer
- set "Input format" to "PHP code"
- Add the code:
ocode
ophp
global $whatisthenodeid;
$nodenid  $whatisthenodeid[0]-nid;
db_query(' PDATE {node_counter} SET daycount  daycount + 1, totalcount
 totalcount + 1, timestamp  %d WHEE nid  %d', time(), $nodenid);


# # # Default front page # # #

Update your "Default front page:" with the View's "UºL" from above.

4.7.x Dome >> Administer >> settings : General settings


( admin/settings )
5.x Dome >> Administer >> settings >> Site information
( /admin/settings/site-information )

# # # End # # #

 c 
  


2| Last modified: September 6, 2009

A block view will appear as a 'block' on your site, meaning it can be put into the sidebars, or any
other region your theme supports. Ôhe same view can provide both 'block' and 'page' views and
they can have very different characteristics.


"  
If checked, Views will provide this view as a block, which then must be enabled by going
to     
>>  . It can be placed in any sidebar/region you like, as with any
other Drupal block. If not checked, the contents of this section will be ignored.
c 
Ôhis setting allows you to specify how the view is displayed in the block. See the
definitions section for more information.
 
Set a custom title for the block.
  
 
Specifies the maximum number of results to display in the block. Blocks may not use
paging.
)
 
If checked, the block will display a link to the page view,  there appear to be more
results to display. It is not valid to check this if the view does not also have a page view
activated.
( 

Check this to simply use the same header that's set on the ^age View, and leave the Block
View blank.
( 

Ôhis is a piece of text that will be displayed before the view results. It may contain
explanatory text, a message, or if you have administrative privileges, it may contain ^D^
code.
 

Ôhe footer appears at the bottom of the view. It may be a short message describing the
view; it may also be, if you have the proper permissions, ^D^ code that can run a snippet.
 !
Ôhe empty text will appear if the view returns no results. It may be a short message
describing the view; it may also be, if you have the proper permissions, ^D^ code that
can run a snippet. NOÔE: If the view returns no results, the view  
and  
will
not appear! If you want the view header/footer to appear when a view returns no results,
you need to duplicate it in the Empty Ôext!

¦
c 
  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: ·arch 8, 2009

If you are investigating the use of the Views module, and would possibly like to embed content
from a view into regular node content, there are a couple contributed modules that can help you
out:

2| Ôhe Insert View module acts as a filter in Drupal that can be enabled for various input
methods.
2| Ôhe Viewfield module adds on a field type for your CCK nodes, and allows you to select
the desired view.

A more advanced option is to embed a View by hand with ^D^. Ôhis can be done in the node
edit page (if you are using an input method with the ^D^ evaluator filter enabled) or via
^D^Ôemplate in your theme's .tpl.php files.

First, we would use views_get_view($view_name) to create a view object, then we'd use
views_build_view($type, &$view, $args  array(), $use_pager  false, $limit 
0, $page  0) to display it.  $%    & ""'   & 
      '

Basically, all that views_build_view requires is a type value (we'll be using 'embed') and a view
object. Ôhe optional variables include an array of views arguments, an option to output the view
in pages, how many results to return (or how many results to return per page), and which of the
returned pages to start on.

As a simple example, I can edit a node and embed a view into it with the following code:

ophp
//load the view by name
$view  views_get_view('sample_view');
//output the view
print views_build_view('embed', $view);


As a more complex example, let's assume that I want to embed a view on all nodes of a specific
type but have different results returned based on the node's title. One way to do this would be to
place the following code in your node-m .tpl.php file:
ophp
//load the view by name
$view  views_get_view('faq_topics');
//output the top three items in the view with the node title as an argument
print views_build_view('embed', $view, array($title), false, 3);


You can also build a view in different ways:

page
^roduce output as a page, sent through theme. Ôhe only real difference between this and
block is that a page uses drupal_set_title to change the page title.
block
^roduce 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
ºeturn an $info array. Ôhe array contains:

2| query: Ôhe actual query ran.


2| countquery: Ôhe count query that would be run if limiting was required.
2| summary: Ôrue if an argument was missing and a summary was generated.
2| level: hat level the missing argument was at.
2| result: Database object you can use db_fetch_object on.

items
ºeturn info array as above, except instead of result, items: An array of objects containing
the results of the query.
queries
ºeturns an array, summarizing the queries, but does not run them.

  ! 2 "  " 


  


2| Drupal version: Drupal 5.x


2| Last modified: June 2, 2009

¦    "    *           
  !  ".

For example, I have two node types: & (  and . In each ) (  node I want to display a
list (view) of the * associated with that particular ) ( . So our 'context-node' is a ) ( 
and our 'listed-node' is an *.

Ôhe trick here is really the Argument Dandling, but first :


We need a way of associating an ¦  with a particular .
A simple method is to add a ££ Node-ºeference field to ‘  nodes. In the Node-ºeference
field configuration:

2| label the field ^  ,


2| choose the 'Select List' widget, and
2| set the '£ontent types that can be referenced:' to î .
2| Now would be a good time to create a couple of new ¦  and associate them with a ^ 
using the ^  select list.

?nd we need a View to embed.

2| £reate a View named ‘ ‘.


2| In the Page fieldgroup: check 'Provide Page View', and select 'List View'.
2| In the Fields fieldgroup: select 'Node: Title'.
2| In the Arguments fieldgroup: select 'Node ºeference: Projects (field_projects)' and set it to
'Display All Values'.

  c     ! 2 .


In order for the Argument to work as a 'context filter' it needs to receive an argument from the
node in which it appears. Dow we  this argument depends on the method for embedding the
view in the node.

For this example we want every ) (  to include a list of associated *, and we don't want
users or editors to change this behaviour; so we will hard-wire it into the theme using the  +
& ( '& '&&. (Ôhere are a couple of drawbacks to this method: [1] it only works with
^D^template themes and [2] this is custom theming, so if you use more than one theme on your
site, you need to create and modify a  +& ( '& '&& in each drupal/theme/$yourtheme
folder.)

After creating a  +& ( '& '&& in our drupal/theme/$ourtheme folder (by renaming a copy
of the node.tpl.php), insert the following code chunk wherever we want it to appear:

ophp
// load the context-node's 'metadata'
global $current_view;
// * define the context-node's NID as the argument
$current_view-args[0]$node-nid;
// * select the name of the view to embed as $view1
$view1  views_get_view('issue_view');
// * define this section for CSS
print 'odiv class"issue_view"';
// * display a subtitle for the view section
print 'oh2' . t($node-title . ' Issues') . 'o/h2';
// send $args to the View's Argument Handler and display $view1 in the
context-node
print (views_build_view('embed', $view1, $current_view-args, false,
false));
print 'o/div';


 
.
Ôhings you might want to change are marked with a *:

1.| * à‘ 
 
   à


 
  :
$current_view-args[0]$node-nid;
Usually $node-nid; does the trick, but I found that a 'relativity module' parent, for example,
required $parent-nid;.
{ther times, depending on the Argument Handler used in the View (?), you may want to pass,
say, the node type by using node-type;.

2 * 
 


 
‘

à

‘:
$view1  views_get_view('issue_view');
Pretty straight forward. If your View is not named issue_view you need to substitute it here.

2 * à‘ 
 ‘
‘

:
print 'odiv class"issue_view"';
If your View is not named issue_view and you want intelligible £SS tags, you need to substitute the
£SS class here.

2 * à‘ î

‘

 
‘
‘ :
print 'oh2' . t($node-title . 'Issues') . 'o/h2';
This will display the context-node's title .... eg ·
‘ 
^ 
¦  - as a title atop the list.
If you don't like clutter, just comment out the line.
If you want it to say just ¦  , use the line print 'oh2' . t('Issues') . 'o/h2';instead.

(     " .


Adding additional views to the node page is very easy, as you can see from this modified  +
& ( '& '&& code which displays a list of relevant * and then a list of related  +
nodes as well:

ophp
// load the context-node's 'metadata'
global $current_view;
// * define the context-node's NID as the argument
$current_view-args[0]$node-nid;

// * select the name of the view to embed as $view1


$view1  views_get_view('issue_view');
// * define this section for CSS
print 'odiv class"issue_view"';
// * display a subtitle for the view section
print 'oh2' . t($node-title . ' Issues') . 'o/h2';
// send $args to the View's Argument Handler and display $view1 in the
context-node
print (views_build_view('embed', $view1, $current_view-args, false,
false));
print 'o/div';

// * select the name of the view to embed as $view2


$view2  views_get_view('how-to_view');
// * define this section for CSS
print 'odiv class"how-to_view"';
// * display a subtitle for the view section
print 'oh2' . t($node-title . ' How-to') . 'o/h2';
// send $args to the View's Argument Handler and display $view2 in the
context-node
print (views_build_view('embed', $view2, $current_view-args, false,
false));
print 'o/div';


?    ?  

Ôhis article was a DUGE help.


Ôhese techniques were used to automatically embed a small image gallery with each node of a
specific type. Ôhe image nodes "know" where they should show up (using nodereference) and a
tiny bit of custom theming to embed the view - magic!

Another approach is documented here: http://drupal.org/node/221919, as it is a little different,


and employs a few different techniques.

c 
  
  


2| Last modified: November 26, 2008

Arguments are parts of the UºL of a view that can be used to reduce the result-set. A classic
example of an argument would be in the case of taxonomy/term/ÔID or tracker/UID. In the
former case, the view is restricted to posts tagged with the associated taxonomy ID; in the latter
case, the view becomes restricted to posts by the specified user.

Ôhere is also a special case where arguments can be embedded into a View's UºL. For example,
the UºL /user/$arg/track would be valid on any /user/DAÔEVEº/track UºL, and the
DAÔEVEº would be passed into the view as the first argument.
A given view can have multiple arguments. For example, you might have blogs as a view, and
provide UID, Year, ·onth, and Day as arguments in that order. Ôhus the UºL might look like
blogs/1/2006/3/15 which would display all blog posts written by user id #1 on ·arch 15th, 2006.
Arguments can also be specified as *, which will be interpreted as 'all values'; so in this case,
blogs/*/2006/3/15 would show blog posts by ALL users on that date.

£   ?   

As of today's update, titles for pages that have arguments now work the way most people
probably thought they should work.

?   

 

If a page has an argument, the title for the last argument given is used. If that argument has no
title, it continues to the previous argument's title; if there are no previous arguments, it uses the
page's title. All of these arguments may use % substitution.

?     

Let's say we have a view that will select nodes with an option to specify the node author and/or
the taxonomy term to which that node belongs. Ôhe first argument is a user ID, and the second
argument is a taxonomy term ID. Both arguments have the J  option set to a summary
view; this means that if we give no arguments, we'll get a summary view for the user ID
argument, which will be a list of users.

Ôhe   (which is the "Ôitle" textbox under the "^age" panel on the Views administration
page) is the title of the page when no arguments are given. Since in our example view, omitting
all arguments results in a summary view of users, we'll set the ^age Ôitle to "Users".

Ôo recap, our first argument is a user ID and the second argument is a taxonomy term ID.
Applying the explanation in the Argument Ôitle Overview above to our example we get the
following order of operations:

D c       


 

1.| If both the user ID (argument 1) and taxonomy term ID (argument 2) are specified, our Title for
the second argument will be used. We set it to "User %1, Term %2" so the resulting title would
be something like "User John Doe, Term Some Term".
2.| If a user ID (argument 1) is given, but not a taxonomy term ID (argument 2), then the Argument
Title for the first argument will be used. In this case, we set it to "Terms for %1" so the resulting
title would be "Terms for John Doe".
3.| If neither argument is specified, the Page Title (the "Title" textbox under the "Page" panel) will
be used resulting in a title of "Users".
      £    !   "

Coming back to our example, what happens if we want to find all nodes under a particular
taxonomy term, but we don't care who the node author is? Ôhis is where the   
and
  
#  argument options come in to play. ildcard is the UºL text that can be used in
place of an argument when you want to return all results for that argument. ildcard Sub is the
text that will be used in the argument title for any %1, %2, etc. substitution.

For our example view, we'll set the ildcard for the user ID argument to "all" and set ildcard
Sub to "(All Users)". Now if we access our view at the path ,-& ,". .
, our view
will return all nodes in the taxonomy term ID 34 belonging to any user and the title of our page
will be taken from the argument 2 Ôitle resulting in something like "User (All Users), Ôerm
Some Ôerm".

?rgument Type

This simply displays the name of the argument.

Default

This option tells Views what to do if an argument isn't specified. The choices are:

2| ºeturn a Page Not Found. In this case, the argument is not optional, and if not specified,
the view simply isn't there, and 404s the user.
2| Show all values. In this case, the argument is completely optional, and if not there is
simply ignored.
2| Display a Summary View. In this case, if the argument is missing Views will not display
the actual view, but instead will get a list of all possible arguments and display a list of
them, with links to the view with the argument, and a count of posts that argument
contains. In the above example, if the User ID argument is set to a Summary View, and
the user goes to 'blogs', views will provide a list of every user with at least 1 blog post.

Title
The title specified for an argument is only used if 1) that argument is the last argument present.
It is used to provide different titles based upon which arguments are present. With the blogs
example above, the actual Title for that view might be "Users with Glog Posts, because if the UID
is not present we'll get a summary view. The title for the UID argument might simply be "Glog
Posts for %1", only showing the user, since if that title is used, the rest of the date is not
specified. Please note that as of Jun 24, 2006 this is a change from previous behavior.

Option

The option field is specific to a given argument; often it is not even present. If it is present, its
usage should be described in the help text for that argument.

Wildcard
The UºL string that can be used in place of an argument when you want to return all results for
that argument, such as "all" or "*".

Wildcard Sub

The text that will be used in the argument title for any %1, %2, etc. substitution when that
argument's Wildcard string was given for that particular argument.

Ôhe following is a list of arguments supported by Views by default. Ôhere can be much more
than this! ·odules can create argument handlers and provide them. As handlers are provided,
they should all provide some form of documentation in the Views help section.

à
î

The node type argument allows users to filter a view by specifying the type of node.

 
¦
  à

The User ID argument allows users to filter to nodes authored by the specified user ID.

 
¦
  à

 à

The User ID argument allows users to filter a to nodes authored or commented on the specified
user ID.

  
 
¦

The argument will filter by a taxonomy term ID. For this argument, set the option to the depth
to search. See taxonomy for more information.

  
 


The argument will filter by a taxonomy term name. For this argument, set the option to the
number of characters, using 0 for full term; use 1 for an A/G/£ style glossary.

à
‘

The argument will filter by the node title. For this argument, set the option to the number of
characters, using 0 for full term; use 1 for an A/G/£ style glossary.



This argument allows users to filter by what year the node was posted, in the form of ££YY.

· 

·onths are specified by the numbers 1-12. Since this argument does not specify a year, it is
recommended that it usually follow a 'Year' argument.


This allows the user to filter a view by the week number from 1-52. It is recommended this
argument follow a 'Year' argument.

· 



This argument combines ·onth and Year into a single argument, specified in the form ££YY··.




This argument is a complete date in the form of ££YY··DD.

à
¦

This argument is a single Node ID.

2| Defining and sending Views Arguments


2| Some use cases of Arguments
2| Views Argument Handling £ode
2| Views Arguments basics

J    c 


  
  


2| Drupal version: Drupal 5.x


2| Last modified: ·arch 30, 2007

)
  
   
   c 
  .

/ 0  & % $1+&  22*  


2 2%  & 3
 2  224"% 2'*  22 
 22'

Getting the right Argument to the View's Argument Dandler can be tricky.
As far as I know, there are only two 'carriers' from which a View Argument Dandler can get the
Argument:

 ,  1

2| As far as I can tell, Views' default (off the peg) Argument Dandlers try to pick out a
particular section (NID, UID, ÔID, etc) from the context-node's UºL (eg
www.site.com/node/23 ... so the NID = '23') and use this as the (first) Argument
($args[0]).
2| Every page has a UºL, so there's always something for the Dandler to work with. But
because UºLs can get messed about so much by modules and such, this method often
seems (I·DO) to yield unpredictable results. Of course if you can predict exactly how
your UºLs are going to be structured, you only need to customise is the View's
Argument Dandling Code to translate the UºL structure into the View's $args array
structure.

À" 3  3" ,1,m  1

2| Ôhe context-node (or module or whatever) itself specifies the Arguments (the  array)
and sends it to the View when calling it, using ",% ,"56 as the carrier.
2| Ôhe downside is that you have to figure out where and how to insert (hack) the following
php code (or similar) into the context-node, module, node.tpl.php, block, or whatever it is
that calls the View into being. For example, the NID is a property of the context-node's
$node_array (eg $node->nid), not the view, so we need to define the Argument within
something that is part of or has access to that context-node's $node array. I·DO this
method is more reliable and predictable ... in a sledgehammer sort of a way ;)
2| Calling the views_build_view function

ophp
global $current_view;
$current_view-args[0]$node-nid;
$view1  views_get_view('view_name'); // change
'view_name' to the name of your view
print (views_build_view('embed', $view1, $current_view-args,
false, false));


 
Ôhis page is a work in progress. I will add to and edit as I get a better grasp of what's going on
and why, but I hope in the meantime it may help other drupaleers struggling up the north face of
Views.
Of course if anyone has any advice, suggestions, theories, explanations or improvements; or
especially if I've misunderstood something - please, please, please  jot them in a comment or
contact me ( ohnG) and I'll gladly incorporate them as best I can.

£ 
       
 #! #
 $%%&
Posted by Gitmaster on  

!""#

$%&î

By replacing the first parameter in the method views_build_view(..) with one listed below, you
can get the return data in a variety of forms. Below is a list of parameters and their return type.
Ôhis information was extracted from the source code.

For example if you created a view to get a list of node id's and wanted those id's to be returned in
the form of an array... You would chose the 'items' parameter as the first argument of the method
call...
$id_list = views_build_view('items', $view1, $current_view->args, false, false));

'page' -- ^roduce output as a page, sent through theme. Ôhe only real difference between this and
block is that a page uses drupal_set_title to change the page title.
'block' -- ^roduce 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. Ôhe array contains:
* query: Ôhe actual query ran.
* countquery: Ôhe count query that would be run if limiting was required.
* summary: Ôrue if an argument was missing and a summary was generated.
* level: hat 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.

Dope this helps,


Bit

#   


  
  


2| Drupal version: Drupal 5.x


2| Last modified: January 23, 2008

    !   ' $ ! (    &

In a nutshell:

  blog/author/$arg

   User: Username is author
 ^osts by %1
  
all
  
# all users

Larger version

Ôhe output of the view will change dependent on the UºL (see one author and every author
(using the wildcard))
Note that the title has also changed - this is because of the '%1' in the 'Ôitle' option under the
Argument Options. In the case of the wildcard being using, the text entered in 'wildcard sub' in
used in place of '%1'.

      !        

In a nutshell:

  node/date (note the absence of $arg - If it doesn't appear in the UºL, it's not necessary for
the user to include it)

  Node: ^osted Year and Node: ^osted ·onth
 "^osts made during %1" and "^osts made during %2 %1" respectively
  
* for both arguments
  
# "all years" and "all months" respectively

Larger version

Ôhe output of the view will change if the user enters a particular year/month combination for the
UºL.
For example, entering 2007/12 as the date will give this:

(You can also see Selecting nodes posted in 2007 vs. Selecting nodes posted in 2008 and
selecting nodes posted in November 2007 vs. selecting nodes posted in December 2007)

Ôhis view can also return all nodes posted within a certain month by making use of the wildcard
for the year argument.

(Full screenshot)

    !   )   

In a nutshell:

 node/recent/$arg

  User: UID Authored or Commented
 ºecent comments on posts and new posts by %1
  
*
  
 all users

Larger version

Combining arguments with sort criteria can give you some pretty nifty views. Ôhis particular
view, when combined with sort criteria like "Comment: Last Comment Date" and "Node:
Created Ôime" will sort the nodes that fulfill your arguments based on the most recently
posted/commented node.
Ôhe argument will return nodes posted by or commented on by the user with the uid specified in
the UºL.

`    *+ 
 

In a nutshell:
 blog/author/$arg (Ôhe ºSS Feed argument doesn't need $arg. ust append '/feed' to any
views UºL with the ºSS Feed argument, and you'll be given an ºSS Feed page.)

  ºSS: ºSS Feed Selector
 ^osts by %1
% ºSS Feed provided by Views
  
*
  
# all users

Large version

Ôhis view is essentially the same view as "Sorting a list of nodes based on the author's name",
which one argument added: the ºSS Feed Selector. Ôhe ºSS Feed Selector argument essentially
gives you an ºSS Feed of your view.

Of course, change an argument in the UºL, and the ºSS Feed correspondingly changes.

(Using wildcards also works in this scenario.)

c 
  (  $ 
  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Audience type: Developers and coders
2| Last modified: July 4, 2009

In addition to the arguments that Views supplies natively, you can also insert your own custom
argument handling code using ^D^ (provided you have the 'use ^D^ for block visibility'
permission). Simply expand the 
  (  $  fieldset and enter your code.

For example:
// Make the first argument 1 if not already set
if (!$args[0]) {
$args[0]  1;
}
return $args;

You can also make changes to the view directly here as well:

// Show full node view, rather than teaser, if an argument exists


if ($args[0]) {
$view-page_type  'node';
}
return $args;

A few notes:

1.| The code should  go between <?php and ?> delimiters; just typed in directly.
2.| The code should return an array of arguments to pass into the view.
3.| You have a number of variables available to you in this handling code: all of the arguments of
the views_build_view function. For full details, please see the documentation above that
function in views.module.

Ôhe following is a list of variables that are ready to use:

î

The type of view, for example 'page' or 'block.'

‘

The current view object.

 

an array of arguments being passed into the view (for example, in the UºL
http://www.example.com/view_url/1/foo, $args[0] is 1 and $args[1] is foo).

 î

a boolean value indicating whether current view is using a pager.

‘‘

the number of rows to retrieve; required if $use_pager is TºUE.

î

a number which indicates what page of the view to start on; used when not using $use_pager
but using $limit, to retrieve only a section of the view.
* ££,*     

Suppose you want to make a block to display on node pages (UºL path node/n). Ôhe block
should show all the items that have a CCK Node ºeference field that link to the current node id.
Dere's a little recipe.

First, in the Arguments section of the view, select Node ºeference:.

In the Argument Code section, enter:


$args[0] = arg(1);

arg(1) is a drupal function that grabs the second argument from the UºL path, in this case the
node id. Ôhe query that views will build will include a DEºE clause that require to equal
$args[0].

For an example of the output, see http://si505.cms.si.umich.edu/node/2.

    + 

You can use this field to dynamically set filters with options that may not exist. For instance, you
could combine with date module and create a filter to list x number dates after a certain day,
which is generated from the UºL. Ôhe real trick here is if you set dynamic filters, you ·USÔ
clear the query cache so views will regenerate it for you. Example code (minus the php tags):

ophp
// Create a timestamp for two days ago
$stamp  time() - (86000 * 2);

// Generate the date parts, using our stamp O the arguments passed in to the
view
$year  $args[0]  $args[0] : date('Y', $stamp);
$month  $args[1]  $args[1] : date('m', $stamp);
$day  $args[2]  $args[2] : date('d', $stamp);

// Add a filter to include only dates later than two days ago
foreach (array('year', 'month', 'day') as $part) {
$view-filter[]  array(
'vid'  $view-vid,
'tablename'  '',
'field'  'node_data_field_date.field_date_value_' . $part,
'value'  ${$part},
'operator'  '',
'options'  '',
'position'  count($view-filter),
'id'  'node_data_field_date.field_date_value_' . $part,
);
}
// IMPOTANT: Invalidate the cached query for this view, as it'll need to be
regenerated on each request
$view-is_cacheable  0;


          

I needed to so something similar to setting dynamic filters and I think I found a very easy way to
do it. Also, it needed to work in combination with panels 2 and pathauto. Dere is my solution,
hopefully my code will help others.

Situation:
I am making a simple event calendar. I want a two-column panel with a list of this month's
events in the left column and the description of the selected event in the right column. Ôhere is a
content type called 'event' and pathauto is configured is configured to have a path like this
(simpified explanation, not the actual pathauto code): agenda/[yyyy]/[m]/[d]/[title]. Of course the
event content type has a cck date field to enter the event's date.

Next I created a view which displays a list with the event's title (as link) and its date. I added 4
filters:
[0] field_datum_value_year=now
[1] field_datum_value_month=now
[2] published=true
[3] node_type=event

·y panel page is set up to override the event node, so when an event node is called, the panel is
displayed with the event in it's right column. Ôhe panel loads the view in the left column. Ôhe
path of this panel page was set to 'agenda'. Ôhe result so far is a panel which displays this
month's events on the left and, when an event in this list is clicked, displays the event node on
the right.

Dere comes the dynamic filter part: I want to access the calendar of other months by passing
arguments to the page. Ôhe path agenda/2008/4/ should show the calendar of april 2008. As you
have seen, I already had the year and month filters in place. Ôhis means that I don't have to create
the filters completely with the argument handling code; I can just override the 'value' variable
when an argument is available. Ôhe code looks like this (without the php tags):

ophp
if ($args[0]) {
$view-filter[0]['value']  $args[0]; // set the value of filter[0]
}

if ($args[1]) {
$view-filter[1]['value']  $args[1]; // set the value of filter[1]
}
$view-is_cacheable  0;


As you can see, I use much less code than quicksketch, because I only set the values that need to
be changed.

Ôhis works perfectly, but there was one problem. hen I was at agenda/2008/4/ (now = 2008/2)
and clicked one of the events in the list (let's call it 'workshop'), the event node was displayed in
the right column, but the view on the left was reset to the default, being the current month. Ôhe
reason for this is, that the path changed to the path of the event node, which has no arguments.
Ôhe actual path was 'node/21' while the path alias was 'agenda/2008/4/16/workshop'. Ôhat's why
I had to add some more code: to make sure that the view didn't reset to the default month when
an event was opened. Now the argument handling code looks like this (again without the php
tags):

ophp
if (!$args[0]) { // if there are no arguments, we may be looking at an event
node
$path  explode('/', drupal_get_path_alias($_GET['q'])); // get the
current path, lookup the path_alias and turn the pieces it into an array
if (($path['0']  'agenda') && is_numeric($path['1']) &&
is_numeric($path['2'])) { // check if $path contains a year and month after
'agenda/'
$view-filter[0]['value']  $path['1']; // set the value of filter[0]
$view-filter[1]['value']  $path['2']; // set the value of filter[1]
}
}

if ($args[0]) {
$view-filter[0]['value']  $args[0]; // set the value of filter[0]
}

if ($args[1]) {
$view-filter[1]['value']  $args[1]; // set the value of filter[1]
}

$view-is_cacheable  0;


If the value you are passing is not an array() you can add this code in to the arguments field
(without the php tags):

ophp
if(!$args[0]){
$view-filter[2]['value']  array(12); // make sure that the value is an
array
}else{
$view-filter[2]['value']  array(); // make sure that the value is an array
}
$view-is_cacheable  0;


£   !'    '  !  '

^ut code below in Argument Dandling Code section of view module.

if (arg(0)  'user' && is_numeric(arg(1))) {


return array(arg(1));
}

Details at:
http://drupal.org/node/111639

For the current node:

if (arg(0)  'node' && is_numeric(arg(1))) {


return array(arg(1));
}

c 
   
  


2| Drupal version: Drupal 6.x


2| Audience type: Developers and coders, Documentation contributors, Site administrators, Site
users, Themers
2| Last modified: September 29, 2010

First I want to state that this might be incomplete or very simplifying in some ways, but after
more than three years with drupal I still haven't completely grasped this.
Ôhis page will try to explain in a very simple way how arguments in views 2 work.

First of all what are view arguments?


Arguments are a way to send information to a view, these arguments can filter the view or
modify them. I use them mostly to create dynamic view filters, filters that change according to
the content that's on the page, usually with block views or views inside quicktabs.

Example:
I have nodes with a certain term, let's say "cars". I'd like to display a block view on each page
with other nodes with the term "cars". Kind of a related articles block.

So, I'll add an argument : Ôaxonomy: Ôerm ID.


Now since most of pages I'll be looking at will look like this:
www.mysite.com/node/##
I want to take that ## (node id or nid) find out what term is assigned to it (in a specific
vocabulary) and then filter my view results according to that nid.

Lets understand the two different types of arguments that are available:
$args and arg() - yes there's a difference.

$args ± are arguments that are being passed to the view, so if you have a page view and it has
this url
www.mysite.com/pageview

then the arguments are what comes after the page view
www.mysite.com/pageview/first/2/third

$args[0] = "first"
$args[1] = 2
$args[2] = "third"

Ôhe second type of argument is the stuff that comes after the website url.
So if I'm looking at a node:
www.mysite.com/node/12

then

arg(0) ="node"
arg(1) =12

so lets take a look at this url again:


www.mysite.com/pageview/first/2/third

arg(0) = pageview
$args(0) = first
«

Ok, let's backup, we've just added Ôaxonomy: Ôerm ID as an argument.


if our pages will look like this:
www.mysite.com/node/12

then no arguments will be passed to the view ($args will be empty), but arg(1) will hold 12 the
valuable node id (nid).
So under the setting:
    
    
 

which should be always, choose



"    
  .
Next we want to manipulate the argument we want to pass to the view (find that term id we want
to filter with). Ôhen choose ^D^ Code.

now this is the code I used, it assumes there is only one term for each node. Ôhis is just to
explain the basics:

ophp
if ($view-display_handler-display-display_plugin  'block' && arg(0) 
'node' && is_numeric(arg(1))) {
$nodenode_load(arg(1));
$term  taxonomy_node_get_terms_by_vocabulary($node-nid, 1); //change the
1 for the vocab id
$args[0]  key($term);
}
return $args;


lets go through it one by one:

ophp
if ($view-display_handler-display-display_plugin  'block' && arg(0) 
'node' && is_numeric(arg(1))) {


we want to make sure that we're dealing here with a block view so:

ophp
$view-display_handler-display-display_plugin  'block'


in addition we want to make sure that the url is what we're expecting that the first argument is 'node'
so:

ophp
arg(0)  'node'


and that the value after the node is a number:

ophp
is_numeric(arg(1)


Next we load the node according to the node id we got from arg(1)
ophp
$nodenode_load(arg(1));


Now we'll fetch the term id from the node:

ophp
term  taxonomy_node_get_terms_by_vocabulary($node-nid, 1);


the '1' is the vocabulary id we're searching in, you can change this according to the vocabulary the term
is in.

Finally we give the view an argument to work with:

ophp
$args[0]  key($term);


we set the first argument to be the term


And we send them all back:

ophp
return $args;


Ôhat's it. Now the view will be filtered to display only nodes with the same term id, as the page
that holds the block.

ͤ Views Argument Handling £ode up Views Fields ͥ

Login or register to post comments $ £ategories: Drupal 6.x, Developers and coders, Documentation
contributors, Site administrators, Site users, Themers, No known problems

£ 
      
 !  
Posted by tweaker on è  
!'
!""

"%(î

I think I watched every Views Argument video and postings we have -- but can't seem to locate
good information on setting up a View comparing Ôerm Names from two different
Vocabulary«. all most there but yet so far away :)

Dere's what I've done so far


`  only see Ôitles from Vocabulary 4 in a block when viewing Node which has an exact same
term name but in a different Vocabulary used by a different content type.

   Vocabulary 4 and 17 are used by different content types

$
   J 

$  
   !   ºelated terms
1) Gave it name
2) Set up a relationship between Vocabulary 4 and 17
3) Checked box = ºequired this ºelationship

$  
 
 
1) Ôaxonomy: Ôerm
2) Use ºelationship
3) Deleted both "ALL" in wildcards
4) Validator options = Ôaxonomy Ôerm
a. Selected Vocabulary 4 and 17
b. Argument type = Ôerm name or synonym choice
c. Ôransform spaces to dashes

    

1) ºequire relationship selected


2) Is one of Vocabulary 4

  
1) Ôitle
2) Ôerms (for tesing only)

ell the filter is working - lol - But  


 when viewing the Node.

Is anyone able to see what I'm missing?

I think I made a tricky choice for my first Argument and ºelationship.

-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
"I would love to change the world,
but they won't give me the source code"
-G

c   
  


2| Last modified: April 5, 2007


Fields are only applicable to a view if either the page or block type is set to List or Ôable view. If
using a purely teaser view,     
 .

Fields tell Views exactly what to display and in what order.

Ôhe Fields section is a variable length list of fields. Ôhe icons to the right can be used to change
the order of the fields, or remove them. Ôo add a field to the list, simply choose one from the
select box and click 'Add Field'.

 
Ôhis is simply the name of the field.

Ôhis is the label that will be associated with the field. If blank, its meaning changes
depending on view type. In List View, blank labels simply won't be displayed. In Ôable
View, however, blank labels will display the Name field as the default label.
( 

Ôhe Dandler is specific to a given field. Not all fields have handlers. It allows you to
choose how a given field is displayed, if there is more than one choice. For example, date
fields have several options to choose from: It can be displayed as an age, or as
short/medium/long dates.
#

If a field can be sorted at all, you can use this field to determine whether or not the 

is allowed to sort it by clicking on the column header in a table view. Ôhis field has no
meaning in a List View.
J  #

If any fields are set sortable, one and only one field should also be set as the default sort.

hat follows are some of the fields that Views supplies by default. Ôhere can be many more
fields than this! ·odules can provide these as they like, but this is a nice overview of what is
easily available.

 $ 
Display the title of the node.
 $7
Display the post time of the node.
 $&
Display the last time the node was updated.
 $&
Ôhe Node Ôype field will display the type of a node (for example, 'blog entry', 'forum
post', 'story', etc)
 $ 
Ôhis will display the author of the node.
7 $87 
Ôhis will display the last comment time.
7 $87  
Ôhis will display the name of the last user to comment on the post.
7 $7 
Ôhis will display the comment count.
-  $ 
Ôhis will display all taxonomy terms associated with the node. Note that this causes one
extra query per row displayed, and might have a minor performance impact.
-  $ )  1 % 
Ôhis will display all taxonomy terms associated with the node that are members of the
named vocabulary. Note that this causes one extra query per row displayed, and might
have a minor performance impact.
-  $
Ôhis will display one of the taxonomy terms associated with the node; if taxonomy terms
were used to filter or sort, it will be the one that triggered the sort or filter. ^lease note
that if your node has multiple terms associated with it, this field can cause your post to
show up multiple times!
-  $  & 
Ôhis will display the description associated with a taxonomy term.

c   

  


2| Drupal version: Drupal 5.x, Drupal 6.x


2| Audience type: Site users
2| Last modified: June 4, 2010

Filters are what are used to reduce the result set of a View to a manageable amount of data. Ôhey
are a critical part of the foundation of this system.

Ôhe filtering system is a compromise between flexibility and ease of use. Ôo be truly powerful,
filters should provide the ability to do an Oº, but as it stands, these filters are all ANDed
together. Ôhat means that every filter is applied. hile the ability to do an Oº would be nice,
unfortunately the level of complexity in the interface to do that is well beyond the benefit that
would be given.

Ôhe order of filters is irrelevant, though they can be re-ordered as a convenience.

uield

This is simply the field being filtered on.

Operator

The operator tells Views H{W to filter, and is part of the 'equation' of a filter. Usually this
appears as a human readable sentence, and by simply reading the fieldname, with the operator
and the value, it is clear what the operator means. For example, "Taxonomy Term", "Is {ne {f",
"...some list of selected terms...".
Value

The Value field varies greatly based upon what field is being filtered, but is usually either a text
box or a select box.

Option

The option field is specific to each field being filtered. The only currently existing option is on
taxonomy terms, where the taxonomy depth is listed as an option. For taxonomy filters, you
cannot specify "all" as a depth but must specify a number. The correct number to use depends
on your site, but 2 will get roughly 90% of the uses. 3 will work for roughly 99% of the cases. The
more you set the more expensive the query so set it to the smallest number that will work for
your situation.

Expose

If a filter is 'exposed' the user will be presented with a widget to control the filter. When the
expose button is clicked, the filter is added to the 'Exposed Filters' fieldset that appears just
below the Filters.

 + 

Exposed filters are shown to the user, so that the result set can be modified. Ôhe typical example
of this is to expose taxonomy as a filter so that the user can select which taxonomy term to filter
on.

Ôhe order of the exposed filters controls the order in which they are presented to the user.

uield

This is the field being filtered; while all of the other fieldsets include an 'Add' button beneath it,
this one does not; to add an exposed filter, go up to the Filters fieldset and click 'expose' on the
filter you want exposed.

Label

This is the label presented to the user.

Optional

If a filter is set optional, an "<All>" choice will be added (if it's a select). If a filter is not optional,
a value must be provided to the view.

uilter settings Default

If a filter is set to optional, and this setting is checked, the actual settings of the filter will be the
default; if this setting is not checked, the default will be set to blank or .
uorce Single

If this setting is checked, any multi-select box available for this filter will be forced into a
dropdown box and only one selection will be allowed. This is typical; dropdowns use less screen
real estate and are easier for people to use.

Lock Operator

If this field is checked, the 'operator' will not be exposed, and the setting in the Filters section
will be used. This setting is typical.

hat follows is a list of filters that Views provides by default. Like other systems in Views,
modules can provide more of these.

à%
)

  

Including this filter will reduce the node set to nodes that have been updated or have new
content since the user last read the node, as well as unread nodes.

à%
^‘ à

Filter by whether or not the node is published. This is recommended for most Views!

à%
  
^

Filter by whether or not the node has been promoted to Front Page.

à%
‘

Filter by whether or not the node is set sticky.

à%
·à à

Filter by whether or not the node is moderated.

à%
î

Include or exclude nodes of the selected types.

à%
 
‘
  

This allows you to filter by whether or not the node author is anonymous.

à%
 
‘
  
 

This allows you to filter by whether or not the node was authored by the logged in user of the
view.

à%
  
 
  à

 à
This allows you to filter by whether or not the logged in user authored or commented on the
node.

à%
‘ ‘ 

This filter ensures that each node may only be listed once, even if it matches multiple criteria.
Use this if multiple taxonomy matches return duplicated nodes.

à%
 


This allows you to filter by a particular user. You might not find this useful if you have a lot of
users.

*%
 
*

Include the node only if the author is a member of the selected role.

  %
 

When filtering by taxonomy term you may specify the "depth" as an option. Please see the
taxonomy help for more information.

  %
 


î‘‘
 

{nly terms associated with the specified will appear in the select box for this filter. When
filtering by taxonomy term you may specify the 'depth' as an option. Please see the taxonomy
help for more information.

  %
+ 


This will filter a view to only nodes that contain a term in the associated vocabulary.

c #
$


  


2| Last modified: June 9, 2009

Ôhe sort criteria on a View controls the order in which views results are presented. In general,
sort criteria are specified by a direction, and the order is important.

For example, if a view is sorted by taxonomy term ascending, and then title descending, then the
entire list of posts will be sorted by what taxonomy term they belong to. (Note: vocabularies
where multiple terms are allowed for this setting will produce apparently nonsensical results!)
Ôhen, all posts which belong to the same term will be sub-sorted by title in reverse alphabetical
order.
£   

atch out for double sorting. Using Sort Criteria and using Default Sorts in the Fields can give
odd results.

uield

This simply says what field to sort by.

Order

Either Ascending order, which means lowest value to highest value (Example: 1, 2, 3, 4 or a, b, c)
or Descending, which means highest value to lowest value (4, 3, 2, 1 or c, b, a).

Option

An option that is specific to a given sort criteria. At this time no sort criteria have an option, but
may in the future.

hat follows is a list of sorting criteria supported by Views by default. ·ore may be available,
supplied by modules with Views support.

à%
 à
‘

Sort by the submission date of the node.

à%
, 
îàà
‘

Sort by the last update date of the node.

à%
‘

Sort by whether or not the node is sticky. £hoose descending to put sticky nodes at the top.

à%
‘

Sort by the node title, alphabetically

* à

Gy choosing random, nodes will be ordered completely randomly. This is a good way to choose X
random nodes from a group of nodes.

à%
 


This allows you to sort alphabetically by author.

 %
, 
 

This will allow you to sort by the date of the most recent comment on a node.

  %
 


This will sort nodes by taxonomy weight and name, as defined in the category administration.

## 
c 
  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: {ctober 13, 2009

Views can have ºSS feeds so that users can read the items in their news reader as they get added
to the view.

1.| enable the "views_rss" module in à‘ ‘  » à


2.| create or edit a view (under à‘ ‘  » ‘ )
3.| in your view, click on the "Arguments" heading to reveal its settings
4.| under "Add Argument", select "ºSS: ºSS Feed Selector", then the "Add Argument button"
5.| select the default as "Display All Values"
6.| save the view as usual, or continue creating the view

Ôhis automatically creates an ºSS feed for the view, and adds a feed icon at the bottom of the
view. It also enables ºSS autodiscovery for that view, so that you can just copy the UºL of the
view into the news reader (also some browsers will make note of the feed so that you can
subscribe to it).

Ôhe feed becomes available at whatever the UºL is for the view, plus "/feed".

Note: to add CCK fields in addition to the Ôitle and Body fields you should look at the Content
Ôemplate module.

Dere is the code to import in Views 1.x (Drupal 5):

$view  new stdClass();


$view-name  'user_feed5';
$view-description  '';
$view-access  array (
0  '3',
);
$view-view_args_php  '';
$view-page  T E;
$view-page_title  '';
$view-page_header  '';
$view-page_header_format  '6';
$view-page_footer  '';
$view-page_footer_format  '6';
$view-page_empty  '';
$view-page_empty_format  '6';
$view-page_type  'views_rss';
$view-url  'rss/$arg';
$view-use_pager  FASE;
$view-nodes_per_page  '5';
$view-sort  array (
array (
'tablename'  'node',
'field'  'created',
'sortorder'  'DESC',
'options'  'normal',
),
);
$view-argument  array (
array (
'type'  'uid',
'argdefault'  '1',
'title'  '',
'options'  '',
'wildcard'  '',
'wildcard_substitution'  '',
),
);
$view-field  array (
);
$view-filter  array (
array (
'tablename'  'node',
'field'  'status',
'operator'  '',
'options'  '',
'value'  '1',
),
array (
'tablename'  'node',
'field'  'type',
'operator'  'O',
'options'  '',
'value'  array (
0  'blog',
),
),
);
$view-exposed_filter  array (
);
$view-requires  array(node);
$views[$view-name]  $view;
Note: Views for Drupal 6 takes a different approach.

ͤ Views Sort £riteria up Views 1 theming ͥ

Login or register to post comments $ £ategories: Drupal 4.7.x, Drupal 5.x

£ 
?  D  £
Posted by mrwendell on  
!
!""#

%

You might be able to get around this by with the Argument Dandling Code option in the views
argument fieldset to flip your arguments around or to flip on the wild card in certain
circumstances.

For me I had one argument then I added the ºSS argument and only one ºSS link showed up.
·y view is set up as follows

viewpath/arg1/rss

hen I clicked on the link on the base ("&.) the like was "&.9. - this returned a
page not found until I went to my first argument and set the wildcard to '*' then everything
worked fine.

For example I used

channel/columns/column+name

here  .  is the view name and "column+name" is the name of an argument.
 . .9. gave an ºSS feed of all the columns and
 . . :. gave the rss feed for the "column+name" column only.

I am using drupal 5.2 and views 5.x-1.6

2| Login or register to post comments

  
 # 
Posted by giorgio79 on è  
$
!""&

-%!

I cannot find views_rss in Drupal 6, any ideas?

ºeview Critical
ClipGlobe - orld Ôravel

****·e and Drupal :)****


Clickbank I^N - Sell online or create a membership site
c   
  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: ·arch 8, 2009

·uch of the power of Views cannot be fully realized until an administrator gets accustomed to
theming. Views may be themed at various levels, with each level providing either more or less
control:

1.| Each field printed may be themed individually (valid in table/list views). This requires
understanding the name of the field you want to theme.
2.| Each view may be themed by type -- meaning a view that provides teasers in page mode and a
list in block mode may have each mode themed separately.
3.| Each view may be completely themed. This requires understanding a bit about what makes up a
complete view.

For  of these functions, the _VIENA·E is optional; if the viewname is not part of the theme
function, you will override theming for  of your views.

   

Views now comes with a new module, views_theme_wizard.module, which will allow you to
generate a theming function and template for your views if you happen to be using a
^D^Ôemplate theme. At the moment it only works for list views, but these are the views that are
actually difficult. Using the wizard is quite simple; select a view and run the wizard. It generates
code for your template.php and a viewname.tpl.php which you can drop right into your theme
directory. You can then make adjustments to this.

Note that if you just want to theme a 'teaser' view, the   way to accomplish this is to
override the teaser function, and change the node_view() function to something like this:

ophp
node_view($node, 'some-identifiable-string');


Ôhen, in your node.tpl.php (or node-type.tpl.php) you can do:

ophp

if ($teaser  'some-identifiable-string')


and theme your node as per the normal node theming.


+   

hen using theming functions, you should consult the Drupal theming documentation for detail
on what this stuff does and how to deal with it. In particular, read Using Ôheme Override
Functions in order to override Drupal's default theming.

function theme_views_view_TYPE_VIEWNAME($view, $nodes);

This is called after all of the header and before any footer information are displayed. This is
likely to be the most commonly used theme function simply due to its relative simplicity. All this
function has to do is loop over the $nodes array and display the data based upon the type of the
view. Gy default, the TYPE may be one of:

2| list
2| table
2| teasers
2| nodes

but plugins could offer other types that may also be themed (and for these you will need
the plugin's theme function name, rather than the plugin type name, ie
theme_views_rss_feed_VIENA·E).

Ôhis function themes a particular view for a particular type, thus not interfering with any
of your other views.

ophp
/**
* Display the nodes of a view as a list.
*/
function theme_views_view_list($view, $nodes, $type) {
$fields  _views_get_fields();

foreach ($nodes as $node) {


$item  '';
foreach ($view-field as $field) {
if (!isset($fields[$field['id']]['visible']) &&
$fields[$field['id']]['visible'] ! FASE) {
if ($field['label']) {
$item . "odiv class'view-label ". views_css_safe('view-
label-'. $field['queryname']) ."'" . $field['label'] . "o/div";
}
$item . "odiv class'view-field ". views_css_safe('view-data-
'. $field['queryname']) ."'" . views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view) . "o/div";
}
}
$items[]  "odiv class'view-item ". views_css_safe('view-item-'.
$view-name) ."'$itemo/divn"; // l($node-title, "node/$node-nid");
}
if ($items) {
return theme('item_list', $items);
}
}

/**
* Display the nodes of a view as a table.
*/
function theme_views_view_table($view, $nodes, $type) {
$fields  _views_get_fields();

foreach ($nodes as $node) {


$row  array();
foreach ($view-field as $field) {
if ($fields[$field['id']]['visible'] ! FASE) {
$cell['data']  views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view);
$cell['class']  "view-field ". views_css_safe('view-field-'.
$field['queryname']);
$row[]  $cell;
}
}
$rows[]  $row;
}
return theme('table', $view-table_header, $rows);
}

/**
* Display the nodes of a view as teasers.
*/
function theme_views_view_teasers($view, $nodes, $type) {
return views_theme('views_view_nodes', $view, $nodes, $type, true);
}

/**
* Display the nodes of a view as plain nodes.
*/
function theme_views_view_nodes($view, $nodes, $type, $teasers  false,
$links  true) {
foreach ($nodes as $n) {
$node  node_load($n-nid);
$output . node_view($node, $teasers, false, $links);
}
return $output;
}

function theme_views_view_VIEWNAME($view, $type, $nodes, $level  N , $args
 N );

When Views attempts to display a view, first it attempts to call


theme('views_view_VIEWNA·E'). If this function does not exist, then it will call
theme('views_view'), which is the default method of displaying a view. As a themer, you can
override either one, but in general it's better to override the specific one.

Ôhe $view argument will be the full definition of the view from the database.

Ôhe $type argument will be either 'block', 'page' or 'embed'. (It can actually be other
things, but anything else will be user defined. ·ore on this later). Ôhis argument is used
to control whether page or block specific display is done.

Ôhe $nodes argument will be an array with all of the information from the database
nicely loaded.

if $level is set to a positive value, this means the view is a summary view, and should be
sent to the summary theme instead of the normal type theme.

ophp
/**
* Display a view.
*/
function theme_views_view($view, $type, $nodes, $level  N , $args 
N ) {
$num_nodes  count($nodes);

if ($type  'page') {
drupal_set_title(filter_xss_admin(views_get_title($view, 'page')));
views_set_breadcrumb($view);
}

if ($num_nodes) {
$output . views_get_textarea($view, $type, 'header');
}

if ($type ! 'block' && $view-exposed_filter) {


$output . views_theme('views_display_filters', $view);
}

$plugins  _views_get_style_plugins();
$view_type  ($type  'block')  $view-block_type : $view-
page_type;
if ($num_nodes || $plugins[$view_type]['even_empty']) {
if ($level ! N ) {
$output . "odiv class'view-summary ". views_css_safe('view-
summary-'. $view-name) ."'".
views_theme($plugins[$view_type]['summary_theme'], $view, $type,
$level, $nodes, $args) . 'o/div';
}
else {
$output . "odiv class'view-content ". views_css_safe('view-
content-'. $view-name) ."'".
views_theme($plugins[$view_type]['theme'], $view, $nodes, $type) .
'o/div';
}
$output . views_get_textarea($view, $type, 'footer');

if ($type  'block' && $view-block_more && $num_nodes  $view-


nodes_per_block) {
$output . theme('views_more', $view-real_url);
}
}
else {
$output . views_get_textarea($view, $type, 'empty');
}

if ($view-use_pager) {
$output . theme('pager', '', $view-pager_limit, $view-use_pager
- 1);
}

if ($output) {
$output  "odiv class'view ". views_css_safe('view-'. $view-name)
."'$outputo/divn";
}
return $output;
}


function theme_views_summary_VIEWNAME($view, $type, $level, $nodes, $args);

If a given view has a summary mode -- in which a listing of possible choices for arguments are
given -- theme('views_view_summary_VIEWNA·E') will be called instead. This is a very good
choice to override, because views doesn't really give the admin many options for how to display
this, and there are many different possibilities.

$view contains the database view information.

$type contains the same information as theme_views_view().

$level is a number stating which argument this summary is for, starting from 0. If a view
has multiple arguments (for example, view/archive/year/month/day) the summary could
be for the year (0), the month (1) or the day (2).
$nodes will be an array of database information for the summary.

$args will be the arguments actually present; in the above example will be an empty array
if $level = 0, but will contain the year if $level = 1 and the year and the month if $level =
2.

ophp
/**
* Display a summary version of a view.
*/
function theme_views_summary($view, $type, $level, $nodes, $args) {
foreach ($nodes as $node) {
$items[]  views_get_summary_link($view-argument[$level]['type'],
$node, $view-real_url) . " (" . $node-num_nodes . ")";
}
if ($items) {
$output . theme('item_list', $items);
}

return $output;
}


function theme_views_more($name);

This simple theme function formats the 'more' link.

ophp
/**
* Format the 'more' link for a view. Personally I prefer [More] but
I've
* been convinced to go with simply 'more'.
*/
function theme_views_more($url) {
return "odiv class'more-link'" . l(t('more'), $url) . "o/div";
}


function theme_views_handle_field_TABENAME_FIEDNAME($fields, $field,


$data);

You can theme each piece of individual data by overriding this theme function. Do so with care,
as using it properly requires understanding what the data you're receiving is.

ophp
/**
* Themeable function to handle displaying a specific field.
*/
function theme_views_handle_field($fields, $field, $data) {
$info  $fields[$field['fullname']];
if ($field['handler'] && function_exists($field['handler'])) {
return $field['handler']($info, $field, $data-$field['queryname'],
$data);
}

if ($info['handler'] && is_string($info['handler']) &&


function_exists($info['handler'])) {
return $info['handler']($info, $field, $data-$field['queryname'],
$data);
}

return check_plain($data-$field['queryname']);
}


function theme_views_filters_VIEWNAME($form)

For 4.7: This theme function lets you change how the exposed filters are displayed.

ophp
function theme_views_filters($form) {
$view  $form['view']['#value'];
foreach ($view-exposed_filter as $count  $expose) {
$row[]  form_render($form["op$count"]) .
form_render($form["filter$count"]);
$label[]  $expose['label'];
}
$row[]  form_render($form['submit']);
$label[]  ''; // so the column count is the same.
return theme('table', $label, array($row)) . form_render($form);
}


For 5.x: This theme function lets you change how the exposed filters are displayed.

ophp
function theme_views_filters($form) {
$view  $form['view']['#value'];

foreach ($view-exposed_filter as $count  $expose) {


$row[]  drupal_render($form["op$count"]) .
drupal_render($form["filter$count"]);
$label[]  $expose['label'];
}
$row[]  drupal_render($form['submit']);
$label[]  ''; // so the column count is the same.

// make the 'q' come first


return drupal_render($form['q']) . theme('table', $label,
array($row)) . drupal_render($form);
}


Ôhe savvy reader will note that a large section of this documentation has, in fact, disappeared.
·ost of it was rendered irrelevant by the compartmentalization of the theming functions. It is the
author's hope that the code snippets will be sufficient to guide you into what needs to be done,
and that later tutorials can provide more interesting information.

2| A simple tutorial
2| Example: Add a 'ºeset' Gutton to Exposed Filters
2| Example: How to £reate a 'Jump ·enu' from a List View
2| Example: How to Display a List View As a ·ock ·enu
2| Example: How to Display a Summary View as a £omma Separated List
2| Example: How to Display a Summary View as a ·ock ·enu
2| Example: How to Embed Two Views on the Same Page
2| Example: How to ·ake Glock View Gehave Differently from the Same Page View
2| Example: How to display Glock view different from default Page view
2| Example: How to provide a view which contains taxonomy headers
2| Example: Vertical Views Tabs layout with teaser to the right of the tabs

 

  


2| Drupal version: Drupal 5.x


2| Last modified: ·arch 8, 2009

 

1.| Download views module.


2.| Enabled views, views ui, and views theming wizard
3.| 'Add' the front page view
4.| £hange the view type to list view
5.| You add the node id field, so we can load the node in the template file.

'  

1.| If we visit oursite.com/?q=frontpage, we see a list of node ids. Gut we can do better. A lot
better.
2.| Go to example.com/?q=admin/build/views/wizard, and select frontpage as the view.
3.| ·ake the theme type simple list
4.| £lick select theme type
5.| Paste all the code in the correct files
6.| Visit example.com/?q=frontpage. tada! Ugly! Yay!

If we look at our function in template.php, we see

ophp
function phptemplate_views_view_list_frontpage($view, $nodes, $type) {
$fields  _views_get_fields();

$taken  array();

// Set up the fields in nicely named chunks.


foreach ($view-field as $id  $field) {
$field_name  $field['field'];
if (isset($taken[$field_name])) {
$field_name  $field['queryname'];
}
$taken[$field_name]  true;
$field_names[$id]  $field_name;
}

// Set up some variables that won't change.


$base_vars  array(
'view'  $view,
'view_type'  $type,
);

foreach ($nodes as $i  $node) {


$vars  $base_vars;
$vars['node']  $node;
$vars['count']  $i;
$vars['stripe']  $i % 2  'even' : 'odd';
foreach ($view-field as $id  $field) {
$name  $field_names[$id];
$vars[$name]  views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view);
if (isset($field['label'])) {
$vars[$name . '_label']  $field['label'];
}
}
$items[]  _phptemplate_callback('views-list-frontpage', $vars);
}
if ($items) {
return theme('item_list', $items);
}
}

We want something simpler.
How about stripping all the complex code, so we end up like this.

ophp
function phptemplate_views_view_list_frontpage($view, $nodes, $type) {
foreach ($nodes as $i  $node) {
$items[]  _phptemplate_callback('views-list-frontpage', array('node' 
$node));
}
if ($items) {
return theme('item_list', $items);
}
}


This should give us the whole node in the view, in a $node object, although now we don't have a $nid
variable.
So, we can edit the views-list-frontpage.tpl.php to this.

ophp
/**
* views template to output one 'row' of a view.
* This code was generated by the views theming wizard
* Date: ---, --/--/----, --:-- --
* View: frontpage
*
* Variables available:
* $view -- the entire view object. Important parts of this object are
* frontpage, .
* $view_type -- The type of the view. Probably 'page' or 'block' but could
* also be 'embed' or other string passed in from a custom view creator.
* $node -- the raw data. This is not a real node object, but will contain
* the nid as well as other support fields that might be necessary.
* $count -- the current row in the view (not TOTA but for this page)
starting
* from 0.
* $stripe -- 'odd' or 'even', alternating. * $nid -- Display the NID of a
node.
* $nid_label -- The assigned label for $nid
*
* This function goes in your views-list-frontpage.tpl.php file
*/

//now we add the stylesheet...


drupal_add_css(path_to_theme() .'/views-list-frontpage.css');

odiv class"view-label view-field-nid"
ophp print $nid_label 
o/div
odiv class"view-field view-data-nid"
ophp print $node-nid 
o/div

Ôhis gives us the same thing, with less code.


e can also do something like the following:

ophp
/**
* views template to output one 'row' of a view.
* This code was generated by the views theming wizard
* Date: ---, --/--/----, --:-- --
* View: frontpage
*
* Variables available:
* $view -- the entire view object. Important parts of this object are
* frontpage, .
* $view_type -- The type of the view. Probably 'page' or 'block' but could
* also be 'embed' or other string passed in from a custom view creator.
* $node -- the raw data. This is not a real node object, but will contain
* the nid as well as other support fields that might be necessary.
* $count -- the current row in the view (not TOTA but for this page)
starting
* from 0.
* $stripe -- 'odd' or 'even', alternating. * $nid -- Display the NID of a
node.
* $nid_label -- The assigned label for $nid
*
* This function goes in your views-list-frontpage.tpl.php file
*/

$node  node_load($node-nid);

//now we add the stylesheet...


drupal_add_css(path_to_theme() .'/views-list-frontpage.css');


odiv class"view-field view-data-nid"
ophp print $node-nid 
o/div

ith this, we can transform it into a table, with very little code, and so it displays the title,
author, ect.
Ôhis is our code for template.php
ophp
function phptemplate_views_view_list_frontpage($view, $nodes, $type) {
$output  "otable";
foreach ($nodes as $i  $node) {
$output . _phptemplate_callback('views-list-frontpage', array('node' 
$node));
}
$output . "o/table";
return $output;
}


And views-list-frontpage.tpl.php:

ophp
/**
* views template to output one 'row' of a view.
* This code was generated by the views theming wizard
* Date: ---, --/--/----, --:-- --
* View: frontpage
*
* Variables available:
* $view -- the entire view object. Important parts of this object are
* frontpage, .
* $view_type -- The type of the view. Probably 'page' or 'block' but could
* also be 'embed' or other string passed in from a custom view creator.
* $node -- the raw data. This is not a real node object, but will contain
* the nid as well as other support fields that might be necessary.
* $count -- the current row in the view (not TOTA but for this page)
starting
* from 0.
* $stripe -- 'odd' or 'even', alternating. * $nid -- Display the NID of a
node.
* $nid_label -- The assigned label for $nid
*
* This function goes in your views-list-frontpage.tpl.php file
*/

$node  node_load($node-nid);

//now we add the stylesheet...


drupal_add_css(path_to_theme() .'/views-list-frontpage.css');


otr
otd
ophp print $node-nid 
o/td
o/tr
Or, even better, we could use theme_table, and not include any external files.

template.php:

ophp
function phptemplate_views_view_list_frontpage($view, $nodes, $type) {
$table  array();
foreach ($nodes as $i  $node) {
$node  node_load($node-nid);
$table[]  array($node-nid);
}
return theme_table(array('Node id'), $table);
}


Beautiful. e can go on to do things like

ophp
function phptemplate_views_view_list_frontpage($view, $nodes, $type) {
$table  array();
foreach ($nodes as $i  $node) {
$node  node_load($node-nid);
$user  user_load(array('uid'  $node-uid));
$table[]  array(l($user-name, 'user/'. $user-uid), l($node-title,
'node/'. $node-nid), $node-teaser);
}
return theme_table(array('Author', 'Title', 'Teaser'), $table);
}


e can also do stuff with cck.


For debugging, use

ophp
function phptemplate_views_view_list_frontpage($view, $nodes, $type) {
$output  "";
foreach ($nodes as $i  $node) {
$node  node_load($node-nid);
$output . "Node ". $node-nid ."obr /opre". print_r($node, 1)
."o/preobr /";
}
return $output;
}


Ôhis will show the whole node object, including any cck fields.

Go wild!
! 4  4   !  
  

  


2| Drupal version: Drupal 5.x, Drupal 6.x


2| Last modified: April 24, 2010

Ôo add a reset button to exposed views filters, add this function to your template.php. (Ôypically,
you'll find that file in /settings/all/themes/·Y_ÔDE·ENA·E. You may also find it in
/settings/all/themes/zen/·Y_ÔDE·ENA·E )

ophp
function phptemplate_views_filters($form) {
$view  $form['view']['#value'];

foreach ($view-exposed_filter as $count  $expose) {


$row[]  drupal_render($form["op$count"]) .
drupal_render($form["filter$count"]);
$label[]  $expose['label'];
}
$form['reset']  array(
'#type'  'markup',
'#value'  'oinput '. drupal_attributes(array('type'  'button', 'value'
 t('eset') )) .'class"form-submit" onClick"window.location  ''
.url($view-url) .'';" /',
'#weight'  19,
);
$row[]  drupal_render($form['submit']) .drupal_render($form['reset']);

$label[]  ''; // so the column count is the same.

// make the 'q' come first


return drupal_render($form['q']) . theme('table', $label, array($row)) .
drupal_render($form);
}



J
5.!

ophp
function hook_form_alter(&$form, $form_state, $form_id) {
if ($form_id  'views_exposed_form') {
$current_display  $form_state['view']-current_display;
$form['reset']  array(
'#type'  'markup',
'#value'  'oinput '. drupal_attributes(array('type'  'button',
'value'  t('eset') )) .'class"form-submit" onClick"window.location  ''
.url($form_state['view']-display[$current_display]-display_options['path'])
.'';" /',
);
}
}


!(  $
 46 ) 4

  c 
  


2| Drupal version: Drupal 5.x


2| Last modified: ·arch 17, 2008

ith Drupal 5 and jQuery, it's possible to do a view-as-jump-menu form -- allowing a user to
choose an item from a select list and then 'jump' to that node. Ôhis interaction requires avaScript
be enabled, but this example also degrades nicely -- if the user does not have avaScript, a 'Go'
button is shown and the form still works.

Ingredients:
* One list view that provides node title and node id, optionally sorted in some way (e.g.
alphabetically).
* Several functions in your 'template.php' file (below)
* A smidge of CSS (also below)

In the code below, I've capitalized the portions which you should expect to customize (e.g.
VIE_NA·E should be the machine name of your view).

m m 
ophp
function phptemplate_views_view_list_VIEW_NAME($view, $nodes, $type) {
$fields  _views_get_fields();
$form  drupal_get_form('view_jumpmenu', $nodes, $view-name, 'CHOOSE AN
ITEM');
return $form;
}

function view_jumpmenu($nodes, $view_name, $initial_label) {


// add the jQuery code which hides the 'Go' button and submits the form on
change
drupal_add_js ('
$(document).ready(function(){
$("input.edit-submit-jumpmenu").addClass("hidden");
$("#edit-nid-'.$view_name.'").change( function () {
this.form.submit();
});
})
','inline');
$options  array();
$options[0]  $initial_label;
foreach( $nodes as $node ) {
$options[$node-nid]  _filter_url_trim($node-node_title, 35); // Just
to trim titles longer than 35 chars
}

$form['#id']  'jumpmenu-'.$view_name; // give it a unique name, in case


you want to have more than one on a page
$form['#attributes']  array('class'  'jumpmenu-form', 'name' 
'jumpmenu-'.$view_name ); // again - for uniqueness and styling
$form['nid-'.$view_name]  array(
'#type'  'select',
'#options'  $options,
'#id'  'edit-nid-' . $view_name,
'#class'  'jumpmenu-item',
);
$form['view_name']  array( // again - allowing for multiples on a page
'#type'  'value',
'#value'  $view_name,
);
$form['submit']  array( // the go button, which will be hidden via jQuery
'#id'  'edit-submit-jumpmenu-' . $view_name,
'#attributes'  array('class'  'edit-submit-jumpmenu'),
'#type'  'submit',
'#value'  t('Go'),
);

return $form;
}

function view_jumpmenu_submit($form_id, $form_values) {


if ( @$form_values['nid-'.$form_values['view_name']] &&
is_numeric($form_values['nid-'.$form_values['view_name']]) ) {
return 'node/'.$form_values['nid-'.$form_values['view_name']];
}
}


£ 
form.jumpmenu-form input.hidden {
display: none;
}
!(  J   c 
) ) 
  


2| Last modified: ·arch 1, 2007

Ôhis is very much like the Summary View as a ·ock ·enu example.

ophp
function THEMENAME_views_view_list_VIEWNAME($view, $nodes, $type) {
foreach ($nodes as $node) {
$output . "oli class'leaf'" . l($node-node_title, "node/$node-nid")
. "o/lin";
}

if ($output) {
return "odiv class'menu'nouln" . $output . 'o/ulo/div';
}
}


!(  J # 


c 
$ #
    
  


2| Drupal version: Drupal 4.7.x


2| Last modified: ·ay 14, 2006

Sometimes the table is just not what you want there, but neither do you want one line per page.
ith this version of the summary you may want it embedded somewhere, because you may run
into trouble with page-sizing. See the embedding example.

ophp
function phptemplate_views_summary_VIEWNAME($view, $type, $level, $nodes,
$args) {
foreach ($nodes as $node) {
$item  views_get_summary_link($view-argument[$level]['type'], $node,
$base);
}
$output  theme('links', ', ');

return $output;
}

!(  J # 
c 
) ) 
  


2| Last modified: February 16, 2008

On the surface, this looks like it's just a 'simple' list. But it turns out it isn't quite so simple,
because to do a menu properly, you need to modify the link returned. hich means you need to
actually know a little bit about how views_get_summary_link functions. A little code exploration
is required to properly write this, but luckily, you're reading an example and that code
exploration was already done for you.

Ôhis used to be a bit more complex, but has actually simplified quite a bit.

ophp
function phptemplate_views_summary_VIEWNAME($view, $type, $level, $nodes,
$args) {
$list  '';
foreach ($nodes as $node) {
$list . 'oli class"leaf"' . views_get_summary_link($view-
argument[$level]['type'], $node, $view-real_url) . "o/lin";
}

if ($list) {
return "odiv class'menu'oul$listo/ulo/div";
}
}


!(     c   


#
  


2| Drupal version: Drupal 4.7.x


2| ^age status: Deprecated
2| Last modified: October 26, 2010

If you want to embed a view using ^D^ in Drupal 6.x or 7.x use the following:

ophp
print views_embed_view('viewname','default');


 %  Ôhe content below is old and outdated.


In this view, the view takes an argument of the Node Ôitle type, set to 1 letter long. Ôhis means
that views/example/A will give all matching nodes that start with the letter A. hat I really
want,
though, is for the top of the view to contain the summary of the view and for the bottom of the
view to contain the current letter.

Ôhe easiest solution is to put the summary view in the header of the view, but one ·USÔ be
careful here; embedding a view within a view could lead to an infinite loop as it tries to replicate
itself to infinity. Fortunately for us, the summary is themed separately from the main view, and
doesn't include header.

So what we'll do is put put a ^D^ snippet into the header of the view and set the Input Filter to
^D^ code.

Ôhis view needs to have just one argument; it's possible to do this with more arguments but you
need to theme the summary as well, and check where you actually are. Be sure that argument is
set to provide a summary!

ophp
// load a second copy of the view -- unfortunate but we don't have access
// to the existing one.
$view  views_get_view('VIEWNAME');

// the array() indicates no arguments, which will provide the summary view.
// We also don't want the pager for this view.
print views_build_view('embed', $view, array(), false, false);


See also the example of the comma separated list summary, which goes well with this.

c
 (     J 
 c  #
 

Let's take two different views, view 1 and view 2, that have exactly the same arguments. You
want the top of view 1 to contain not the summary of view 2, but view 2 itself, with the same
arguments view 1 is currently being provided.

Ôhe solution is to put the following ^D^ snippet into the header of view 1 and set the
corresponding Input Filter to ^D^ code:

ophp
// This is a new variable introduced in Views module revision v.1.94;
// it conveniently gives one access to the current view (in this example,
view 1)
global $current_view;
// et's now load view 2
$view  views_get_view('VIEW2NAME');
// $current_view-args contains the arguments view 1 is currently being
provided with;
// we can now build view 2 with exactly the same arguments as view 1
print views_build_view('embed', $view, $current_view-args, false, false);


Note: if you have multiple Views applied to your home page, and the secondary views (the ones
being called into the main View) don't have UºLs entered, it will cause the 404 page page to
show a secondary View instead of the 404 page content. Ôo solve this, simply enter UºLs for all
the Views being applied to the page.

Site ºecipe - DOÔO: Create mulitple Views on one node with paging - check it out here:
http://drupal.org/node/85720.

!(  ) c "


J 
 
 #c 
  


2| Drupal version: Drupal 4.7.x


2| Last modified: ·ay 1, 2006

 $1   &  " % 0& & -& 


  & %     "'

Let's say you have a simple view that is something like 'newest posts in with some taxonomy
ÔEº·.'. You want the view as both a page view and a block view, and you want the [more] link.
No problem you say. But then you discover that they both must be the same type -- but you
really want
it to be a list view as a block, and a teaser view as a page. No problem.

First, set the view up as a List View by default. Ôell it to include the [more] link. e'll override
its default behavior in page view.

Ordinarily, the [more] link only appears if it thinks there are actually more entries to see; we
don't want that behavior in this case because the [more] link is going to different information.

ophp
function phptemplate_views_view_VIEWNAME($view, $type, $nodes) {

if ($type  'page')
// Done before theming so theme can change it if it wants.
drupal_set_title(views_get_title($view));

if ($view-header) {
$header  check_markup($view-header, $view-header_format, false);
$output  "odiv class'view-header' id'view-header-$view-
name'$headero/divn";
}
switch ($type) {
case 'block': // ist View
if (count($nodes)  0) {
$output . theme('views_view_list', $view, $nodes);
if ($view-block_more && count($nodes)  $view-nodes_per_block) {
$output . theme('views_more', $view-url);
}
}
else {
return;
}
break;
case 'page':
$output . theme('views_view_table', $view, $nodes);
break;
}

return "odiv class'view' id'view-$view-name'$outputo/divn";




!(    " 



 
   " 
  


2| Drupal version: Drupal 5.x


2| Last modified: ·ay 4, 2008

By default a view in drupal 5 displays in "block view" all the fields that it displays in the "page
view"

as described by merlin
http://drupal.org/node/245234#comment-802873
one can use theming or create a different view

here is the solution using theming to get a different block view

function THEMENAME_views_view_table_VIEWNAME($view, $nodes, $type) {

$fields  _views_get_fields();
if ($type  "block"){
foreach ($nodes as $node) {
$row  array();
foreach ($view-field as $field) {
if ($field['label']  "FIEDABE1" || $field['label'] 
"FIEDABE2"){
$cell['data']  views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view);
$cell['class']  "view-field view-field-$field[queryname]";
$row[]  $cell;
}
}
$rows[]  $row;
}
// return theme('table', array(''), $rows); //use this if you want no
table header
return theme('table', $view-table_header, $rows);

}else if ($type  "page"){


foreach ($nodes as $node) {
$row  array();
foreach ($view-field as $field) {
$cell['data']  views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view);
$cell['class']  "view-field view-field-$field[queryname]";
$row[]  $cell;
}
$rows[]  $row;
}
return theme('table', $view-table_header, $rows);
}

your view has to be formatted as table

change ÔDE·ENA·E, VIENA·E (optional - can get rid of it)


replace FIELDLABEL1 and FIELDLABEL2 with the labels that identify
the fields you want displayed

the "page" part of the code is the default behaviour (not changed)

Ôhe code is probably not the best available but I was looking for this for some time
and I thought that someone might find it useful.

!(  
" "  
    !   

  


2| Drupal version: Drupal 5.x


2| Last modified: ·ay 15, 2008

One thing that is really handy is to be able to format a list like this:

2| TEº·
o| node title ...
o| node title ...
o| node title ...
2| TEº·
o| node title ...
o| node title ...
o| node title ...

A great example would be recipes:

2| £hinese
o| Dou ·iao -- Dou ·iao is a...
o| Geef and Groccoli -- Descriptions are good
o| Szechuan Pork -- Dig your fork into...
2| Italian
o| Lasagna -- Noodles and sauce
o| Golognese -- ·eat meat and sauce
o| Linguine alle Vongole -- £lams make this dish...

And so on...

Views can sort things this way, but it has no facility to add headers. hy? ell, we had to stop
somewhere. Ôhe good news is, this is actually not too difficult to accomplish! e set up our
theme as a List View, given the fields we want to put in. e could do this as a table view as
well, but we'll have to adjust our theme slightly. Ôhat is left as an exercise to the reader.

1st create a view and specify it as a ^age view and view type is "List View." Ôhe name of your
view is referred to as VIENA·E in the code below.

In order to designate what we want to group by, we'll give it a special label so that we can
identify it in code. I'll call this XYZZY, which is actually literal (unlike the _VIENA·E that I
always use). hat this means is that in the 'label' entry of the field, I put 'XYZZY'. Ôhe theme,
here, will take that out of the list and keep it as the header. If you want to call the field something
else, make sure to change "XYZZY" in the template.php below to the field name you want.

Be sure to put the field you want as a header both in your FIELDs section and your SOºÔ
section; otherwise it'll be a jumble!

  %  

Add this code (without the ophp  tags) to your template.php file.

ophp
function phptemplate_views_view_list_VIEWNAME($view, $nodes, $type) {
$fields  _views_get_fields();

$taken  array();

// Set up the fields in nicely named chunks.


foreach ($view-field as $id  $field) {
$field_name  $field['field'];
if (isset($taken[$field_name])) {
$field_name  $field['queryname'];
}
$taken[$field_name]  true;
$field_names[$id]  $field_name;
}

// Set up some variables that won't change.


$base_vars  array(
'view'  $view,
'view_type'  $type,
);

foreach ($nodes as $i  $node) {


$vars  $base_vars;
$vars['node']  $node;
$vars['count']  $i;
$vars['stripe']  $i % 2  'even' : 'odd';
foreach ($view-field as $id  $field) {
$name  $field_names[$id];
$vars[$name]  views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view);
if (isset($field['label'])) {
if ($field['label']  'XYZZY') {
if ($header ! $vars[$name]) {
$new_header  $vars[$name];
}
}
else {
$vars[$name . '_label']  $field['label'];
}
}

if ($new_header) {
if ($items) {
$main_items[]  theme('item_list', $items, $header);
}

// reset values for the next one.


$items  array();
$header  $new_header;
$new_header  '';
}
}

$items[]  _phptemplate_callback('views-list-VIEWNAME', $vars);


}
if ($items) {
$main_items[]  theme('item_list', $items, $header);
}
if ($items) {
return theme('item_list', $main_items);
}
}


  $ %  & 

Create file called "views-list-VIENA·E.tpl.php" (this can be created by theme wizard or you
can just make your own) in your theme directory. Ôhis will control what each item listed in your
view looks like.

ophp
/**
* views template to output one 'row' of a view.
* This code was generated by the views theming wizard
* View: VIEWNAME
*
* Variables available:
* $view -- the entire view object. Important parts of this object are
* compliance_wizard_monthly, .
* $view_type -- The type of the view. Probably 'page' or 'block' but could
* also be 'embed' or other string passed in from a custom view creator.
* $node -- the raw data. This is not a real node object, but will contain
* the nid as well as other support fields that might be necessary.
* $count -- the current row in the view (not TOTA but for this page)
starting
* from 0.
* $stripe -- 'odd' or 'even', alternating. * $description -- This will
display the description associated with a taxonomy term.
* $description_label -- The assigned label for $description
* $title -- Display the title of the node.
* $title_label -- The assigned label for $title
* $body -- Display the Main Content.
* $body_label -- The assigned label for $body
* $name -- This will display all taxonomy terms associated with the node that
are members of oemComplianceo/em. Note that this causes one extra query per
row displayed, and might have a minor performance impact.
* $name_label -- The assigned label for $name
*
* This function goes in your views-list-compliance_wizard_monthly.tpl.php
file
*/
// This optionally adds a new stylesheet that you can get from the wizard
output.
// This line, nor the CSS file are necessary if you just want to do styling
in your
// theme's styles.css file.
drupal_add_css(path_to_theme() .'/views-list-VIEWNAME.css');


odiv class"view-field view-data-name"


ophp print $name
o/div

odiv class"view-label view-field-title"


ophp print $title_label 
o/div
odiv class"view-field view-data-title"
ophp print $title
o/div

$   &

Add the stylesheet "views-list-VIENA·E.css" in your theme directory. (You get this file from
the theme wizard as well.) Note that you don't need to include this if you just want to add the
CSS styling directly in your theme's styles.css file.

/* *
* views template to output the stylesheet to customize a view.
* This code was generated by the views theming wizard
* View: VIEWNAME
*
* The class selectors are filled with a single comment line.
* You should complete each selector according to your liking.
*/

.view-label {
/* insert your css code for this element here */
}

.view-field {
/* insert your css code for this element here */
}
.view-field-name {
/* insert your css code for this element here */
}
.view-data-name {
/* insert your css code for this element here */
}
.view-field-title {
/* insert your css code for this element here */
}
.view-data-title {
/* insert your css code for this element here */
}

Ôhen if you go to the UºL you specified in your Views module for this View, you should see the
list as categorized by the field "XYZZY".

`
"   
  
  


2| Drupal version: Drupal 5.x


2| Last modified: ·arch 30, 2008

I've come up with a cool variation on this snippet that allows you to group nodes by a date field.
I've used it to create a news clipping archive that's sorted and grouped by the year that the clips
were published.

Ôo do this, I created a CCK node type called "News Clipping" and created a "^rint Date" using
CCK's associated date module. So, every clipping node has a custom date field that's available to
the views module. In my custom view, I've given the print_date field the label "Date" - you'll
need to change that to whatever you want in the view.

Dere's the code:

ophp
function phptemplate_views_view_list_palm_in_print_by_year($view, $nodes,
$type) {
$fields  _views_get_fields();

$taken  array();

// Set up the fields in nicely named chunks.


foreach ($view-field as $id  $field) {
$field_name  $field['field'];
if (isset($taken[$field_name])) {
$field_name  $field['queryname'];
}
$taken[$field_name]  true;
$field_names[$id]  $field_name;
}

// Set up some variables that won't change.


$base_vars  array(
'view'  $view,
'view_type'  $type,
);

foreach ($nodes as $i  $node) {


$vars  $base_vars;
$vars['node']  $node;
$vars['count']  $i;
$vars['stripe']  $i % 2  'even' : 'odd';
foreach ($view-field as $id  $field) {
$name  $field_names[$id];
$vars[$name]  views_theme_field('views_handle_field',
$field['queryname'], $fields, $field, $node, $view);
if (isset($field['label'])) {
if ($field['label']  'Date') {
if ($header ! date("Y", strtotime($vars[$name]))) {
$new_header  date("Y", strtotime($vars[$name]));
}
}
else {
$vars[$name . '_label']  $field['label'];
}
}

if ($new_header) {
if ($items) {
$main_items[]  theme('item_list', $items, $header);
}

// reset values for the next one.


$items  array();
$header  $new_header;
$new_header  '';
}
}

$items[]  _phptemplate_callback('views-list-palm_in_print_by_year',
$vars);
}
if ($items) {
$main_items[]  theme('item_list', $items, $header);
}
if ($items) {
return theme('item_list', $main_items);
}
}


**Note the use of strtotime and date functions to create the correct header.

!c
c   

  
    
  


2| Drupal version: Drupal 5.x


2| Last modified: une 18, 2009
It takes only two changes to the tabs.css to accomplish this.
Ôhis assumes that you already have a view with horizontal tabs (as opposed to list or teaser or
full nodes) in place.

For whichever particular view you want to do this for (assuming you don't
want to do it for every instance of views tabs), just add this bit of css
to your style.css (replacing the myview with the name of your own view):

.view-content-myview ul.anchors {
float: left;
}

.view-content-myview .anchors li {
float: none;
}

·y teaser was rendered a little bit high relative to my tabs so I also added this:

.view-content-myview .fragment {
padding-top: 20px;
}

If you make a page view of your tabbed view, then you can study the source code in your
browser and learn where you might further customize your css.

For example, I thought the boxes around each tab looked clunky in this layout so I replaced them
with just a single vertical divider between the tab and the teaser:

.view-content-myview .anchors a{
border-left: none;
border-top: none;
border-bottom: none;
padding-bottom: 10px;
padding-right: 15px;
}

c 

  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: ·arch 8, 2009
Ôhe following tutorials will assist you in learning the basic functionality of using views.
"Snippets" are bits of ^D^ code that will modify views; other pages are more full-fledged
tutorials on building different types of views.

2| Using the Views ·odule: An Introductory Screencast


2| 20 Steps to Views Dappiness
2| A beginners Guide to Using Views with Screenshots (a.k.a. ·aking an archive using
views)
2| Dow to make your Ôaxonomy Query View more flexible using Argument Dandling Code
2| Ôutorial #1: ·ake a "New ^ages" block
2| Ôutorial #2: ·ake a page view called "·odule News"
2| Ôutorial #3: Create two tabs to sort taxonomy view alphabetically and by created time

  c ) ¦




#
 
  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: ·arch 8, 2009

Ôhis screencast is available at


http://rapidshare.com/files/78037463/drupal_views_screencast.mp4 and http://blip.tv/file/553914

Ôhis screencast covers the installation and configuration of the views module, as well as:

2| £reating a new view (both page and block)


2| Adding arguments to the url for a page view
2| Using views to create an ºSS feed
2| Using fields to customize the layout of list and table views
2| {verview of filters and exposed filters
2| Gasic Performance considerations of views

Ôhis is the script for the screencast:

  

Ôhis screen cast is going to teach you the basics of using the views module in drupal. First we
have to download the views module. Ôo do this, go to http://www.drupal.org/project/views and
click on download.

Once the download is complete, extract the views module.

Once the extraction is finished, move the files into the modules folder.
£     c  - 

Ôo configure views, go to the modules page, scroll down, and make sure that all the views
components are enabled. Once everything is working as it should, there should be an extra tab
under site building - views.

£   c  

Say i want to create a blog replica using views. Ôo do this, go to views, and click add. Enter a
name. Because this is going to be a page and not a block, I have to select 'provide page view'
under page. Enter a url and a title as you see fit. Because I want the most recent posts to come
first, I have to add a particular sort criteria - node created time, and change the default sorting to
descending.

? ?  

Views can also filter a list based on arguments passed to it in the url. For example, if you only
wanted to see posts by one user in particular, you would add a placeholder argument to the url by
typing '$arg' and defining the argument. Ôo do this, go to arguments and add the relevant
argument type. In this case, you would want 'uid as author' because you're selecting posts by one
user.
Under title add recent posts by '%1'. Ôhe '%1' tells the views module that it has to replace it with
the value of the first argument. Similarly, using '%2' would tell the views module to replace it
with the value of the second argument.

A wildcard is a value for the argument that will return all applicable values. If used in this case,
it would return all the posts no matter which user wrote them. ildcard sub is just the text that
the views module would use in the title instead of '%1' when the wildcard is used.

Ôhe output of this view is a page that changes the contents of the list shown dependent on the
argument in the url entered.

Ôhere are a number of arguments that you can use, one of which is 'taxonomy term name'. If you
use this argument along with a vocabulary that posts are tagged with, it is possible to display a
list of posts with a certain tag.

*+

Views can also create a ºSS feed for any list. For example, to add a ºSS feed to our blog, I
would edit the view and add a special argument, 'ºSS feed selector'. It is special because it does
not need an argument placeholder in the url. Simply append '/feed' to a view which has a ºSS
feed selector argument, and you will be given a ºSS feed page.
£   .

In addition to pages, views can create blocks. Ôhe steps to create blocks are almost identical to
the steps to create pages with a few major differences. Instead of selecting 'provide page view',
you have to select 'provide block'. Also, you don't specify a url. Instead, you go to site building
and click blocks. Ôhen, you find your created block and select the location that you want your
block to appear in. Once you click save blocks, the page will reload with your block in the
location you've chosen.

£   c  

You can customize certain aspects of your created views. An example of this is changing the
fields that the block will show. For example, if you would like author's name, time created and
the title of the post instead of the full post or a teaser post, such a view is easily set up. Ôo
customize the fields, the view has to use either list view or table view. Dowever, it does not
matter whether the view is going to be a page or a block. Once the type of view is selected, the
fields must be added. In this case, we are going to add the post title, the date it was posted and
the author's name. You can arrange the fields in any order you like. e are going to arrange it in
the order author's name, date posted, then title of post. Once the arrangement is to your liking,
simply click save to have your view use your customized layout.

+ / + 

Another feature drupal provides is exposed filters. Exposed filters are essentially filters that are
accessible to any visitor of your website, while acting just like normal filters. Ôo use an exposed
filter, you first have to create a normal filter, then click expose.

One example of exposed filters is limiting your search by keywords/taxonomy. Ôo do this, you
have to expose 2 filters: 'search:Index' and 'Ôaxonomy:terms'. Once you do this, you will be able
to search for your words in posts with a certain keyword/taxonomy term.

As you can see, selecting a tag and using a search term gives a more accurate result than simply
selecting a tag or using a search term by itself.

0      

Ôhe performance of views is dependent on 2 things: how complicated your view is, and how
heavily loaded your database is. If your view is complicated, for example a view with many
different fields such as author name, date posted, date updated, comments, etc, that means that
each time your view is accessed, your database is going to get many requests as views does a
separate request for each field. Ôhus, if your database is heavily loaded, the performance would
be slower. Conversely, if your view is relatively simple, and your database load is light, the
performance of views would be much faster. Dowever, you shouldn't have to worry much about
your views performance unless you're running a very big site.
One way to speed up views is to reduce the number of queries to the database that need to be
made to display a given view. Ôhe easiest method is to reduce the number of fields shown in a
particular view, such that fewer queries are needed to display that view.

À #  c ( 


  


2| Drupal version: Drupal 4.7.x, Drupal 5.x


2| Last modified: December 18, 2008

First things first. A View is a LISÔ! List, list, list. A List of stuff on your website. You want
Views because we're not all happy with the way Drupal builds lists out-of-the-box, and we want
to customize our lists.

Install the module from http://drupal.org/project/views. It has an install file, so it works really
nicely in 4.7. Upload it to your modules directory, then browse to the modules section in admin
and enable the Views module and the views_ui module. Ôhat's it.

Enable the module for the users you want to be able to create views using the admin -> access
control menu.

Go to the Views menu item under Settings. Looks intimidating, right? Not really.

Ôhere are many things you can do with Views that go far beyond this configuration interface, but
we'll leave that for now. If you are ambitious later, go look at the snippets section mentioned
above. You (yes, YOU) can import some of these canned Views using the import tab.

So, a simple exercise. 20 steps to views happiness. Let's create a view (list, remember?) that is
displayed in a block. Ôo the right you can see a block that says "New Forum Ôopics" and lists
titles. Let's build a View that creates a list sort of like that.

1.| Click on the "Add" link.


2.| Give it a name "LatestFront^ageItems" [spaces not allowed]
3.| Don't check anything in the access section because we want everyone to be able to see
our cool block.
4.| Give it a description for the Blocks admin page: "Latest Front ^age Items"
5.| Next is the ^age section. e're not making a page (but Views pages are cool too!) we're
making a block, so just leave this section alone.
6.| Now go to the Block section and check the "^rovide Block" box because we want Views
to provide us with a Block for our View.
7.| Give it a title: "Cool Block, eh?" (I'm a Canuck)
8.| Let's show five items in our Block, so input "5" in the "nodes per block" section. A node
is an item like a story or a blog entry. e want a list of item titles (not a table or a list of
teasers or a big list of full items) so leave the default "List Items" the way it is. You can
play with this later to see what it does.
9.| If you wanted your block to be a preview of a page of the same View, you would check
the "·ore" link. e chose not to make a ^age for this view, so we won't do that. You can
have both ^age and Block Views of the same View.

OK, let's take a little break here. hat's a View again?

Dere's another take on it: a View is just a way of looking at all your stuff on your
website. ith real world objects you can have several views. You can look from
above, from below, from the side, etc. You can look at it through filters that show
only certain spectrums of light. You can look really close, or from far away.

Viewing the content of your website using Views ·odule is the same thing. Dow
do you want to see your content? In a list that has node titles, then dates, then
times published? Do you want to see it as a table or a standard list of items? Do
you want to sort alphabetically, from the latest, or from the earliest? All these
ways of viewing your stuff can be a single "View". So we're building a block that
will give us a particular view of our content on our website.

10.|So, we're in the block section of the Views administration, and we just chose not to
provide a "·ore" link because we're not generating a page for this View. Now we click
on "Deader". Do you want to put some stuff at the top of the block? Use the Deader area.
Check "Use ^age Deader" and Ôype in the box "Ôhis is is my really brilliant introductory
paragraph. Dope you like it." Ôhe text box can take any kind of input, including DÔ·L
and probably images, though I haven't tried that yet. Now ÔDAÔ is amazing.
11.|Close the Deader section and click on Footer. Same story here. Let's put in a footer.
Check the "Use Footer" box and type in the text box "Ôhanks for looking at my Cool
Block. It's my first one."
12.|Close Footer and click on "Empty Ôext". Ôhis is here in case the View doesn't generate
any results. It could say something like "Ôhis View sucks" or "Come back later for a
better View" but we're going to make sure there is some content in our View by picking a
big section of content, so don't bother with that for now. ust remember it's there in case
you need it.
13.|Close Empty Ôext and now we're at "Fields". e need some fields here or our block will
be empty and we'll wish we had put something in empty text. (Oh, by the way, you can
save your View and go back in to edit it some more now if you are worried about your
six month old daughter hitting the keyboard). Fields are just the parts of your content you
want to display in your View. So the default one that is staring you in the face is a good
place to start. "Node: Ôitle" is just the Ôitle Field of your content items. Ôhe title. ust the
title. Node is a fancy word for a piece of content. So we want to add this to our View
because want our list to contain the titles of our content pieces. Click "Add Field". Now
you have a field for your view. Look at all the extra stuff you can configure to the right of
the field name. hen you get better you can play around with the options on these, but
for now, let's keep it simple and go with one field with default configuration.
14.|Close Fields and skip Arguments (try this later) and go to "Filter". So far we have told
Views we want a list of Nodes with Ôitles in it, but we don't want a list of ALL the nodes
on our site. e want something more useful. Let's make a list of all nodes that have been
published to the front page. Ôhat way, no matter where people are on our site, they can
see the list of front page nodes. So, click on the list of Filters and choose "Node: Front
^age" and "Add Filter".
15.|Skip "Exposed Filters" and click on "Sort Criteria". e want our nodes to be listed in our
block with the most recent node first. So, select "Node: Created Ôime". Now, when you
add it, it comes back with an option to sort by ascending or descending. e want latest
items at the top, so descending.
16.|Save your View!
17.|Now, go to Blocks and you'll see your Views Block listed in the inactive blocks. Enable
it and put it where you want. In Drupal 4.7 you can put it in lots of places, but for this
excersise, put it in the right column.
18.|Save your blocks configuration and you new Views Block will show up on the right.
Notice the list has titles of items published to front page, listed with the newest on top.
Amazing, eh?
19.|Now, go back to Views and start playing around with all the different setting for your
block you just created. Change the filters, add arguments, add Fields, take them away
again. Each time you save your changes, the block you created on the right hand side will
refect the changes. Ôhis is a great way to get started with Views and learn the beginnings
of what is possible. Ôhink about what you can do with pages! Oh, and in pages you can
set the path, so http://example.com/my/cool/views/page and you can even put a link
to your cool views page in the menu, right from the views configuration interface. Ôhat is
so amazing. Ôhat's Drupal 4.7.
20.|Go have a beer, because you are now well on your way to understanding Views and you
need a bit of time to reflect on all the possibilites. It is a lot more powerful than this
simple excercise, but its now up to you to read the documentation at
http://drupal.org/node/42592 and learn more.

Dave fun. You now have much more power at your fingertips.

Cross-posted at http://blurt.info

Ôhis node in ºussian: http://setegnom.com/node/200

You might also like