76
d r u p a l . o r g Views Module

Drupal: Views Module Guide

Embed Size (px)

DESCRIPTION

Views ModuleOriginal document from drupal.org, i just create the pdf to be more accessible. --Ready to Print--

Citation preview

Page 1: Drupal: Views Module Guide

d r u p a l . o r g

Views Module

Page 2: Drupal: Views Module Guide

2

Getting started (3-4)

o Create a page to list users by role (5-6) o Create a block of recent stories (7-8) o Create an RSS feed of user posts (9-10) o Create a block of author's recent blog posts (11-13)

• What's new in Views 2 (14-23) • What is Views? (24)

o Arguments (25-26) o Fields (27) o Filters (28) o Relationships (29) o Sorts (30)

• Displays (31) o Default display (32) o Page display (33) o Block display (34) o Attachment display (35) o Feed display (36)

• Output styles (View styles) (37) o Unformatted output style (38) o Grid output style (39) o RSS output style (40) o Table output style (41) o List output style (42) o List summary style (43) o Unformatted summary style (44) o View row styles (45)

Comment RSS item row style (46) Fields row style (47) Node RSS item row style (48) Node row style (49)

• Embedding a view into other parts of your site (50) • Menu options (page display) (51) • Path options (page display) (52) • Theme information (53)

o Using CSS with Views (54-55) o Using Views templates (56-57)

• Updating your views from Views 1 to Views 2 (58) • View types (59) • What are overrides? (60) • Views' API (61)

o Describing tables to Views (62-66) o Using default views in your module (67-69) o How Views handlers work (70-71) o How Views plugins work (72-73) o Upgrading your module Views 1 to Views 2 (74) o Integrating the Node Example module (75-78)

Page 3: Drupal: Views Module Guide

3

Getting started

For those new to Views, it can be a complex system that appears totally overwhelming. The good news is that the UI is designed to compartmentalize everything; this means that for the most part, you can ignore the parts you're not interested in. Start small and build your way up.

Because of this, the edit UI can seem overwhelming at first, but there are really just a few things you have to know. The rest you can find through exploration. The Views Edit UI image, below, gives an overview of what you'll find on the edit UI.

The Views Edit UI

Notes: 1) Every view has a number of displays which represent where output will be placed. If you're familiar with the original Views 1, you could set a view to be a 'page', with a URL (path), or a block that could show up in a sidebar. With Views 2, you can add as many displays as you like. In addition, you have the default display which contains the basic settings, but doesn't actually show up anywhere.

2) When you click on the link for an item, a form will open up. For browsers with smaller resolutions, you may have to scroll down a little to see this form. If a form is open, the item its attached to will be highlighted.

3) Overrides mean that a particular display is not using default settings. When you create a new display, many of its settings will start off using default values. This will be indicated by italics and a lighter color. If you change these values without first overriding them, you will change the default value for all displays that use them.

Page 4: Drupal: Views Module Guide

4

4) Some items, particularly styles, have additional settings. Ordinarily when you update a style, if it has additional settings you will automatically see that form next. Often, you will need to go directly to those settings.

5) You can safely leave a view page to go and do other things. If you come back, the view will still be there, stored in a cache. Keep in mind, however, that while you do this, that view is locked, meaning another user cannot edit this view without breaking the lock. Breaking the lock will discard your changes.

It helps to have something particular in mind that you want to accomplish when using Views. Here are a couple of ideas and a brief sketch of how to accomplish what you want.

• Create a page to list users by role • Create a block of recent stories • Create an RSS feed of user posts • Create a block of author's recent blog posts

Page 5: Drupal: Views Module Guide

5

Create a page to list users by role

In this example you will create a page view listing users on your site. Through this step-by-step process, you will become familiar with some basic steps in creating a view, and familiarize yourself with the Views User Interface.

1. Creating a new view

Go to add new view. Give your new view the name 'user_list', description 'A simple user listing.', tag 'users', type 'User' and click Next.

2. About the Interface

You have been brought to the Views User Interface. As you start, you are editing the "Default" options for the view. In the 1st column on the left you can see the drop-down menu offers 'block', for example, to select settings specific only to block views. In the remaining columns, you will be able to add or change options by clicking on links or icons. These options will then appear below this main area. Most likely, you will need to scroll to see the options appear. As you make changes, these options will appear in bold until you save your view.

3. Creating a page display; choosing a URL and creating a menu link 1. In the 1st column, ensure that 'Page' is selected in the drop-down menu, and click Add

Display. 2. Next we'll define the path for this page. A page must have a path, and we define it early

so that Views doesn't warn us "Display Page uses path but path is undefined." Locate the Page settings in the 2nd column, and click the None link next to the Path setting. In the options editing area that appears below, set the path to 'user_list' (or something else if you prefer) and click Update.

3. Next to Menu setting, Click the No menu link. In the options which appear below, select Normal menu entry, and set the title to 'User list' and click Update.

4. Scroll up to Basic settings, in that same 2nd column, and click the No link next to Use pager. Below, in the options, select Full pager and click Update default display.

4. Selecting the fields to display 1. In 3rd column locate the Fields options. Click the + icon to add fields. 2. Scroll down to Defaults: Add fields. In the Groups drop-down menu select 'User', then

check the following fields: User: Created date, User: Delete link, User: Edit link, User: Last access, User: Name and User: Picture. Then click Add.

3. You will be taken through the fields you added one at a time. Click Update default display to go to each next field. Leave the default options on all fields except Delete link; change that field's label to 'Operations'.

4. Scroll back up to Fields and click the ↑↓ icon to rearrange fields. Down below, drag the Name field, by dragging its four-sided arrow, to the top. Drag the Delete link (Operations) field to the bottom, and the Edit link field just above it. Then click Update.

5. Seeing what we've done so far

At this point, you have done enough to create a valid view. If you scroll down, you will see a preview of your view. If it doesn't show already, click the Preview button; but generally this display updates automatically whenever you finish working in one of the mini forms.

6. Styling the view as a table; combining related fields into columns 1. Under Basic settings, in the 1st column, click the Unformatted link next to the Style

setting. In the options below, under Page: How should this view be styled, choose Table and click Update default display.

2. You will be taken to a Page: Style options form to edit the table settings. Locate our Edit link field in this mini form, and notice the Column drop-down. Change this drop-down to show Operations. In the Separator column next to the Operations field, type ' | ' (note the spaces around the | symbol). Check all of the Sortable checkboxes, and set Default sort to Name. When finished, click Update default display.

7. Filtering the user list to exclude unwanted entries 1. Click the + icon next to Filters. 2. In the Groups drop-down menu select 'User', then check the User: Name filter, and click

Add.

Page 6: Drupal: Views Module Guide

6

3. Select Is not one of and enter 'Anonymous' in the Usernames box. Click Update default display.

8. Adding an argument to list users by role dynamically 1. Scroll up to Arguments, and click its + icon. 2. Check the User: Roles argument, and click Add. Set the title to '%1' (don't type the

quotes), and under Action to take if argument is not present select Summary, sorted ascending. Leave the other settings as they are. Click Update default display, and click Update through the prompts that follow to accept their default values.

9. Saving the view

Finally, click the Save button to save your work. At the very top, click View "Page" to go to your new view!

Page 7: Drupal: Views Module Guide

7

Create a block of recent stories

In this example you will create a list of nodes of the content type "story", to be shown in a block. Through this step-by-step process, you will become familiar with some basic steps in creating a view, and familiarize yourself with the Views User Interface.

1. Creating a new view

Go to add new view. Give your new view the name 'recent_stories', description 'Recent Stories', tag 'story', type 'Node' and click Next.

2. About the interface

You have been brought to Views User Interface. As you start, you are editing the "Default" options for the view. In the 1st column on the left you can see the drop-down menu offers 'block', for example, to select settings specific only to block views. In the remaining columns, you will be able to add or change options by clicking on links or icons. These options will then appear below this main area. Most likely, you will need to scroll a bit to see the options appear.

3. Selecting the fields to display 1. In 3rd column locate the Fields options. Click the + icon to add fields. 2. Scroll down to Defaults: Add fields. In the Groups drop-down menu select 'Node', then

check the following two fields: Node: Post date, Node: Title. Then click Add. 3. You will be taken through the fields you added one at a time. Make the changes specified

below. For the Post date field: Delete the 'Post date' label. Change the Date format to

Custom, and the Custom date format to 'F j, Y, g:i a' (do not type the single quotes; for the meaning of these letter codes, click on the PHP docs link under that box to arrive at the explanation). Click Update.

For the Title field: Delete the 'Title' label. Select Link this field to its node. Click Update.

4. Scroll back up to Fields and click the ↑↓ icon to rearrange fields. 5. Drag the four-sided arrow next to Node: Title so that it appears above Node: Post date.

Click Update to save the new field order. 4. Filtering to story nodes only

1. Click the + icon next to Filters. 2. In the Groups drop-down menu select 'Node', then check the Node: Published and Node:

Type filters, and click Add. 3. Select the Published checkbox. Click Update 4. Select Is one of and check Story in the Node Type field. Click Update.

5. Sorting to show most recent first 1. Scroll up to Sort criteria and click the + icon. 2. In the Groups drop-down menu below, select 'Node', then check Node: Post date, and

click Add. Alternatively, you may instead check Node: Last comment time, or Node: Updated/commented date, or Node: Updated date.

3. Select Descending Sort order. Click Update. 6. Refining the basic settings

o In 1st column under Basic settings locate these options: Items to Display setting, click 10. Change the '10' to '4'. Click Update Style setting, click Unformatted. Change to List. Click Update.

7. Adding a block display for custom options 0. In the dropdown on the left, ensure that Block is selected, and click Add Display. 1. Under Block settings, click the None link next to the Admin setting. Change Block:

Block admin description to 'Recent Stories'. 8. Saving the view

Click Save to save your work.

9. Instructing Drupal to show the block

Finally, you should tell Drupal to show this block. Configure your block by going to admin/build/block. Locate the block in the list: it is labeled Recent Stories. Place this block in a

Page 8: Drupal: Views Module Guide

8

region and click Save. You may click Configure to set a different title, to determine which roles can view the block, and on which pages it appears; If you want your block on the front page only, enter '<front>'.

Page 9: Drupal: Views Module Guide

9

Create an RSS feed of user posts

In this example you will create a Feed display to show nodes by individual users, dynamically selected through the URL. You will become familiar with the Views 2 interface, as well as learn how to use an argument to pull in a user name and use it in a dynamically created path.

A feed is a data format that places your site's content into a file that can be read and displayed by news reader programs. When visiting a site, you may notice a small RSS transmission icon, whereby clicking on it, you can subscribe to the site's most recent content. This makes it easier for your visitors to keep up to date with your website. You can also use this format to aggregate information into other sites. For more information, please watch a video from Common Craft about RSS in plain English.

Note, Drupal automatically creates a feed for your website, but you may want to create feeds with specific information. In this case, a list per user.

1. Creating a new view 1. Go to add new view. Give it the name 'user_feed', description 'A feed of user nodes.', tag

'users', type 'Node' and click Next. 2. About the Interface. You have been brought to the Views User Interface. As you start, you are

editing the "Default" options for the view. In the 1st column on the left- you can see the pull-down menu offers 'Feed', for example, to select settings specific only to RSS views. In the remaining columns, you will be able to add or change options by clicking on links or icons. These options appear below this main area. Most likely, you will need to scroll to see the options appear. As you make changes, these options will appear in bold until you save your view.

3. Change default display 1. Under Basic Settings in the 2nd column, click Row style: Fields 2. A menu loads below, Defaults: How should each row in this view be styled, check the

Node option, and click Update. 3. This loads another options menu, Defaults: Row style options click Update.

4. Create the RSS view 1. In the 1st column, select 'Feed' in the drop-down menu, and click Add Display. 2. Under Basic Settings in the 2nd column, click Row style:Missing style plugin 3. Note, options appear below the Views Interface, you may need to scroll to see Feed: How

should each row in this view be styled tick Node, then Update

4. This loads the next options menu- Display type: select "Use default RSS settings", click Update.

5. Set the path for accessing your feed 1. In the 2nd column under Feed settings, click Path: None 2. In options below Feed: The menu path or URL of this view enter in the path with an

argument feeds/%/rss.xml 3. Click Update

6. Set up your arguments to say which user's nodes to display 1. To the right of Arguments, click the + sign to add and argument 2. In the Feed: Add arguments menu that loads below, select User in the pull-down menu 3. Check the box User: Name, click Add 4. Scroll down to options to find Case in path: select Lower case 5. Check the box Transform spaces to dashes in URL 6. Click Update default display

7. Sort to show most recent at top of feed 1. Scroll up to Sort criteria in the right most column and click the + icon. 2. In the Groups drop-down menu below, select 'Node', then check Node: Post date, and

click Add. 3. Select Descending Sort order. Click Update.

8. Set filters to hide unpublished entries 1. Click the + icon next to Filters. In the options below, select Node under Groups drop-

down menu, choose the Node: Published filter, and click Add. 2. Check the box Published. Click Update default display

9. Test 1. Click Save 2. Under Live preview type in the name of a user, in lowercase, replacing spaces with

dashes, click Preview.

Page 10: Drupal: Views Module Guide

10

3. You should test and find your feeds at URLs like http://yoursite.com/feeds/user-name/rss.xml

4. You can use this path for aggregating on another site. You can also attach the RSS feed to another display of view to make the feed link appear on that display.

Page 11: Drupal: Views Module Guide

11

Create a block of author's recent blog posts

In this example you will create a context-sensitive block that shows the titles of recent blog entries by an author when viewing one of their posts. This will demonstrate using Views arguments to dynamically filter a view's contents at display time.

Before working through this example, enable the Blog module and populate some entries from a few different users.

Creating the View

The first step is creating a view for our recent blog entries block. Because the block will show the titles of blog entries, this view is considered a "Node" type. Go to add new view, enter the following properties, and click Next:

View name recent_blog_entries

View description List of recent blog entries for a given author.

View tag blog

View type Node

Generating a list of blog entries

It will be much easier to see the view progress if we can see it doing something. In this section, we will create a basic view displaying blog entry titles.

1. In the third column, locate the Fields area. Generally speaking, fields are the pieces of information that you want to display in the view (in this case, node title). Click the + icon to add a field.

2. Scroll down to Defaults: Add fields, below the settings table. A large selection of fields will be available.

3. In the Groups drop-down menu, select Node. This will limit the list to only the default fields exposed by Node module.

4. Scroll down the list, select the Node: Title field, and click Add. 5. You will now be presented with settings for the Node: Title field. Delete the label from the Label

field, so that each individual node title is not prefixed with the word "Title." Additionally, check the Link this field to its node box so that visitors who see an interesting title can click directly on it to read the blog entry to which it belongs.

6. When finished, click Update. If you scroll down to the Live Preview section, you should now see a list of several node titles; however both blog entries and other node types will be in the list. Let's fix that.

7. In the fourth column, locate the Filters area. Filters limit the results displayed in the view, and we can use this to our advantage here by showing node titles only from blog entries and not every type of node. Click the + icon to add a filter.

8. As before, scroll down to the Defaults: Add filters section, select Node from the Groups select box to limit the list of options to only those exposed by Node module.

9. Scroll down and select the Node: Type field and click Add. In the settings page that appears, leave Operator as Is one of and select Blog entry under Node type. Click Update when finished.

10. Now, by scrolling down to Live preview, you'll see that the list only shows blog entries.

Adding context with arguments

While filters are very useful for limiting the results of a view when the condition is always consistent (for example, a view of blog entry nodes should always be filtered by the blog entry type), something filters can't do is smart decision-making based on the page context. In our case, we want the view to display a different list of blog entries when looking at a post by user 'admin' than we do when looking at a post by user 'member', and filters won't be able to help.

Page 12: Drupal: Views Module Guide

12

Luckily, there's another way to filter a view's content: arguments. Through arguments, Views are able to obtain additional context (typically via dynamic URLs with IDs in them) and can take this context into consideration when displaying the view.

Let's walk through adding and configuring an argument to our view so that we can change its contents based on post author.

1. In the third column, locate the Arguments area. Click the + icon to add an argument. 2. Because we are basing the view around content authors, this time under Groups select User.

Check User: Uid and click Add. 3. The Defaults: Configure Argument User: Uid settings page has a lot going on, but only a few

things that need our attention. 4. The Title field here, unlike the Title field under Basic Settings, can be based upon the context

that the view is being displayed in. Change the title to 'Recent entries by %1.' %1 will later be expanded to the user's name (based on the User: Uid argument) when the view is displayed.

5. Under Action to take if argument is not present, there are a variety of options, ranging from displaying a 404 or a 403 page to simply displaying all values in the view. In our case, if an argument isn't specified (which it won't be, since this view will be displayed in a sidebar block, not as a page with its own URL), we want to give it a default one to act on. Select Provide default argument.

6. Assuming JavaScript is enabled in your browser, you should now get another selection for Default argument type. Select User ID from URL, which will then provide a new option, Also look for a node and use the node author. Select it. This will cause Views to first see if it can figure out a user ID from the current URL (for example, user/1). If it can't, it will instead check to see if the current page is a node page (such as node/42) and, if so, take the user ID from the node's author field instead.

7. Validator options provide a useful way to control what kind of arguments your view will accept. Select User as the Validator. By default, changing this setting will check the incoming argument and ensure it's a valid user ID; if not, the view will be hidden from the page.

8. Once you have changed the argument's title, default argument, and validator options, click Update to save your changes.

9. You'll notice that now the Live preview no longer shows anything. Did we just break the view? Fortunately, no. It's merely abiding by our wishes to hide itself if there is no valid user ID given to it. Try entering a '1' in the Arguments box and clicking Preview. You should now see a list of only user 1's blog entries.

Creating the block

So the live preview is now showing basically what we want. There's just one problem: we have no way to stick what we've done so far into a sidebar block! Let's fix that by adding a new Display.

1. In the first column, under Defaults, there is a select box containing entries such as Page, Feed, and, yes, Block! Select Block and click Add display.

2. There's not much else to do here as far as Views is concerned. Under Block settings, click the None link next to Admin and fill in a description for the block in the administrative interface, such as: 'Recent blog entries by author.' and click Update.

3. Save your work by clicking the Save button at the bottom of the Views interface. You should receive a message that the view has been saved.

4. Next, navigate to the blocks interface and drag the 'Recent blog entries by author' block to the right sidebar region (or similar) and click Save blocks.

5. You'll notice this appeared to do nothing. No block shows in the sidebar. But remember, we are looking at an adminitrative page; we are not looking at a page that would provide a user ID context. Navigate to the main blog listing and click on an entry there. You should now see a sidebar block, titled something like "Recent entries by admin," with a list of blog entries beneath it.

Finishing touches

There are still a few remaining things to do before our view is complete. For example, we said that the block was to show recent blog entries, but instead it's showing them in the order they were entered, with oldest on top. Additionally, even unpublished entries are showing in the list currently.

Page 13: Drupal: Views Module Guide

13

1. Return to the recent_blog_entries view edit page. 2. Add an additional filter by clicking the + icon in the Filters section in the fourth column. 3. Change Groups to Node and select Node: Published. Click Add. 4. Under the Published selection, choose Yes and click Update. 5. To handle sorting, locate the Sort criteria area, just above filters, and click the + icon there. 6. Under Groups, again select Node. From the list of options, check Node: Post date and click Add. 7. In the settings page, change Sort order to Descending. This will place the newer posts on top of

the older ones. Click Update when finished. 8. Finally, Save the view for your new settings to take effect.

Page 14: Drupal: Views Module Guide

14

What's new in Views 2

Views 2 is the newest major release of Views and it is specifically coded for Drupal 6. Views 2 retains all of the core functionality of Views 1, together with a completely revamped user interface and a large set of new features which greatly expand upon the original feature-set of Views 1. This document is a side-by-side comparison of Views 1 versus Views 2 from a user's perspective, detailing the UI changes, some new ways to perform old tasks, the cool new features of Views 2 and how these features can be used to address some of the shortcomings of Views 1.

Admin interface

The first thing that pops out after you install Views 2 is the radically different admin interface:

Views 2 admin interface

compared to the old comfy Views 1 interface:

Views 1 admin interface

Page 15: Drupal: Views Module Guide

15

The new admin interface performs the same functions as the old -- listing all the views in the system, providing links to add or import views and a link to Views Tools -- but has been compacted, with each view displayed as a paragraph style-row compared to the table of Views 1 and set of filters on top to ease locating views among a large list.

Context-help is available by clicking the small blue question-mark icon. Context-help in Views 2 is provided by the Advanced Help module, so make sure to install that together with installing Views 2. The small blue help icons will be available in various parts of the Views UI. In particular, look for them as part of the description of a display, when setting style options, and in various editing sections such as path, menu and the like.

Several new attributes of each view are visible in the filter header:

1. Tag - This is just another label for organizing and sorting views. Tags can be any text. Views that are provided by modules will often be tagged together to make it easy to find them.

2. Display - In Views 1 each view query was tied to its display; in other words your fields, sorts, filters, and arguments could only be displayed in the single page or block display provided in the view definition. In Views 2, view displays have been decoupled from view queries - it is now possible to have multiple page, block, and feed displays from a single view. More on view displays later.

3. Type - Views 2 view types are radically different from Views 1 types. Views 1 types basically defined how the node list displays were styled - you had Full Nodes, Teaser List, Table View, and so on. In Views 2 view display styles have been broken out into the separate Style attribute. View types now refer to the primary table on which information for the query will be retrieved which controls what arguments, fields, sort criteria and filters are available. Views 2 view types are discussed later.

Adding a view

So let's jump in and add a view. For this example, we're going to create a user view, which will display a list of users.

Adding a view

The first step in adding a view is simply entering a name (only alphanumeric characters, no spaces) a description, tag, and the view type. To get the user view, we selected the User radio button.

Page 16: Drupal: Views Module Guide

16

Configuring the new view

This might be the 2nd whoa moment as the interface here is also completely revamped from Views 1.x. The best way to summarize is to say all the pieces from the Views 1.x interface are still there...just in different places. Fields, arguments, sort critera and filters are all still there there, just in new AJAXY-flavours.

Let's start by adding some fields:

Adding fields

Page 17: Drupal: Views Module Guide

17

Clicking on the [+] icon next to the word Fields unfurls a section beneath the view information with all the available fields grouped by Comment, File, Node, Node revision, Taxonomy and User, and probably a few others. This is a general paradigm for the Views 2 interface -- clicking on a widget or link unfurls a section beneath the view information with the relevant interface. Usually, what is being edited will be hilited in yellow, as well.

When adding items, you can use the Groups drop-down box to show only a subset of the fields available according to the above groups, or select All to see all fields available, which is what was selected when the section unfurled. For our example, we're selecting the 'User' group and adding the User: E-mail, User: Name and User: Picture fields.

Adding fields

Once we add our fields they show up in the Fields section of the interface. We will be walked through each field we added, so keep clicking update, even if you don't make changes to the field and you will see the next one.

The fields we added can be rearranged by clicking the up/down icon, right next to the add icon we used earlier. We can also remove a field using the same interface.

Page 18: Drupal: Views Module Guide

18

Rearranging fields

From here, the fields can be dragged up and down by grabbing the little drag handle on the left and moving them where you like. Making a change to any part of the view by clicking update usually triggers a refresh of the view preview which is conveniently located right below the main interface.

Views preview

Page 19: Drupal: Views Module Guide

19

Now that we have some fields set up we can turn our attention to Basic Settings for the view.

It's important to note that all the interface elements pertain to the current Display selected for the view. As mentioned before a view can have multiple displays. The first time you create a view you'll be manipulating the Default display. You can add displays using the Add Display button, whose Basic Settings are completely different from each other; this lets you have as many displays of a view as you would like all sharing items such as Sort Criteria, Filters and Arguments but different display settings like Title, Style, Fields, and Pager settings. Also, any display you add automatically inherits display settings from the default display initially, so you can keep a core of common settings in your default display and add additional settings for every other display.

Adding a Page display

Let's stick with the Default display and twiddle some settings. We can set the Title to "User View 1" and the Style to Table. As mentioned earlier, view styles in Views 2 correspond more to view types in Views 1 (remember, List, Table, Teasers, Full nodes).

Selecting a Views 1 View Type

Page 20: Drupal: Views Module Guide

20

In Views 2, view styles control how a view display looks. These styles are significantly different from the Types in Views 1; in particular, types have been 'broken up'; there is now the style as well as the row style which focus on different parts of the output.

A breakdown of View output

We change the style by clicking on the current style on the left hand side of the View information area.

Selecting a Views 2 Display Style

Page 21: Drupal: Views Module Guide

21

We're given the style options of Grid, List, Table and Unformatted. Additional display styles can be added by modules which have Views style plugins. Choosing a style reveals a "settings" button which you can click to configure the style you've chosen. In the shot below we've selected and are configuring the Table style, which we're using to produce a more compact output than we had earlier.

Selecting and configuring the table style

... TODO: Finish this document ...

Page 22: Drupal: Views Module Guide

22

What is Views?

The views module allows administrators and site designers to create, manage, and display lists of content. Each list managed by the views module is known as a "view", and the output of a view is known as a "display". Displays are provided in either block or page form, and a single view may have multiple displays. Optional navigation aids, including a system path and menu item, can be set for each page-based display of a view. By default, views may be created that list content (a Node view type), content revisions (a Node revisions view type) or users (a User view type). A view may be restricted to members of specific user roles, and may be added, edited or deleted at the views administration page

The "building block" design of the views system provides power and flexibility, allowing parameters to be specified only when needed. While an advanced view may use all of available parameters to create complex and highly interactive applications, a simple content listing may specify only a few options. All views rely on a conceptual framework that includes:

• Fields, or the individual pieces of data being displayed. Adding the fields Node: Title, Node: Type, and Node: Post date to a node view, for example, includes the title, content type and creation date in the displayed results

• Relationships, or information about how data elements relate to one another. If relationship data is available, like that provided by a CCK nodereference field, items from a related node may be included in the view

• Arguments, or additional parameters that dynamically refine the view results, passed as part of the path. Adding an argument of Node: Type to a node view with a path of "content", for example, dynamically filters the displayed items by content type. In this example (shown with Clean URLs enabled), accessing the view through the path "http://www.example.com/content/page" displays all posts of the type "page", the path "http://www.example.com/content/story" displays all posts of the type "story", and "http://www.example.com/content" displays all posts regardless of type)

• Sort criteria, which determine the order of items displayed in the view results. Adding the sort criteria Node: Post date (in descending order) to a node view, for example, sorts the displayed posts in descending order by creation date

• Filters, which limit items displayed in the results. Adding the filter Node: Published (and setting it equal to "Published") to a node view, for example, prevents unpublished items from being displayed

• Displays, which control where the output will be seen. Every view has a default display, which doesn't actually display the view anywhere, but is used to hold the default settings for the view, and is used when the view is called programmatically if another display is not specified. Much more useful to users are the page display, which gives a view a path and allows it to be the primary content of a page, or the block display which allows it to appear as secondary content on other pages.

• Arguments • Fields • Filters • Relationships • Sorts

Page 23: Drupal: Views Module Guide

23

Arguments

Arguments are input. While they often come from the URL, they don't always so please don't be shocked when they don't. Each display type may have its own source for arguments. Block displays have no source of arguments at all; they cannot pull arguments from the URL, and often require use of the default argument PHP code in order to get arguments. The argument default plugins can be used to get arguments into a block view. See "Provide default", below.

In general, arguments are used to filter the view, and in that sense they have a very close relationship to filters, but that isn't necessarily true for every argument. Arguments can be used for any purpose, really; the extent of what the argument does is up to the developer of the argument, but the arguments that come with Views are almost entirely filters.

A typical use of an argument might be to reduce a view to a single node, a single user, or nodes with a given taxonomy term.

Action to take if argument is not present Ignore

The argument is removed from the view as though it weren't there and all results will be displayed.

Hide view / Page not found The view will remove itself entirely if the argument is not present; for a block this means it simply won't a appear. For page views the View will return a 404 and present a "Page not found" error.

Display empty text The value of the empty text will be displayed.

Summary The view will attempt to display a summary of arguments available, based upon the view, and provide links to the view with those arguments. Summaries have their own style handlers as well as options. The default summary style simply displays a list of arguments with a count of entries found per argument. This special mode is a very powerful part of Views.

Provide default If no argument is given, a default argument can be selected. The method of choosing the default argument is selectable and pluggable.

Wildcards

All arguments have a 'wildcard', which is an argument that means to use all values. In practice, it is the same as 'Ignore' above, where the argument is simply removed and the view is created without the argument. The wildcard title is used in titles and breadcrumb trails.

Default arguments

Default argument selection is available only if the action to take is "Provide default". When that is selected, a new fieldset will appear letting you choose what the default argument will be. Views provides the following default selectors by default (but other modules may add more):

Fixed entry You may directly enter what the argument will be. This is not a variable, it will always be the same argument.

Node ID from URL This will attempt to find a Node ID from the URL, and is primarily useful for the Node: ID argument (though other arguments that use Node IDs, such as the CCK Node Reference argument, will find it useful too). For example, when visiting the path 'node/1' or 'node/1/edit' it will know that the '1' in that path is a node ID and use it.

User ID from URL Like Node ID from URL, this will attempt to find a user ID from the path. It also includes an option to look for a node and use the node author as the user ID.

User ID from logged in user You can use this to easily default a menu item to the logged in user. For example, if you created the path 'blogs' and gave it a User: ID argument with this default, 'blogs' would go to the user's own blogs, and blogs/1 would go to User ID 1's blogs.

Page 24: Drupal: Views Module Guide

24

Please bear in mind that the selection of default argument happens only if an argument is not provided. If using a display that has no argument source, such as a block, this will be the case 100% of the time. However, if using a display that reads arguments from the URL, this will happen only if the URL did not contain an argument.

Argument validation

Arguments can also have validators, which are pluggable systems used to ensure that arguments fit within certain parameters. When a validator is chosen, it may provide some settings for the validator, including the action to take if an argument is presented, but it fails to validate. These actions are generally the same as the default actions above, excluding the ability to provide another default.

If a view provides a menu option, such as a tab, if the argument does not validate the tab will not appear.

This sytem can have other validators plugged in; by default, Views provides:

Basic validation Ensures that the argument is present. A PHP NULL value (from eg. PHP default argument code) will invalidate.

Node Ensure that the argument is a valid Node ID. You may select which types of node the validator will accept.

Taxonomy term Ensure that the argument is a valid taxonomy term. This includes options to limit to specific vocabularies and can transform the argument to the right type depending upon the actual argument. Set the Argument Type option to the actual type of data that the argument being used is expecting.

PHP Code You may enter arbitrary PHP code, similar to the php block visibility code, to determine if the argument is valid or not.

Page 25: Drupal: Views Module Guide

25

Fields

Fields are the individual pieces of data being displayed. Adding the fields Node: Title, Node: Type, and Node: Post date to a node view, for example, includes the title, content type and creation date in the displayed results).

Fields may not appear on every display, because not all style plugins actually use fields. For example, the 'node' row plugin simply displays the node through Drupal's normal mechanisms, and fields are not involved.

For the most part, the field settings should be self explanatory. Fields will appear in the order that they are arranged in, and they will usually appear with the label they are given.

Page 26: Drupal: Views Module Guide

26

Filters

Filters are used to reduce the data set that Views provides. That is to say, without any filters applied, Views will return all of your content. You don't want that, so at least some filters must be used.

Some very commonly used filters:

• The 'Node: Published' filter is used to restrict a node View to only nodes that are are have the 'published' box checked. This can be very important to prevent users from viewing content they should not have access to.

• The 'Node: Promoted to front page' filter can be used to show only nodes that have the 'promote to front page' turned on.

• The 'Node: Type' filter is useful for showing only certain types of nodes. Let's say you wanted users to see only nodes that were 'book' nodes, or a combination of 'book' nodes and 'staff-blog' nodes. This filter allows you to select exactly that.

• The 'User: Current' filter will show only nodes that the logged in user has authored. • The 'Node: Post date' filter can be used to show only nodes posted before, after, or between a

range of dates.

The above list is only a tiny fraction of the filters available in Views, referenced here to give an idea of the kinds of tasks filters can accomplish.

Page 27: Drupal: Views Module Guide

27

Relationships

Relationships allow you to expand the query to include objects other than the base query. This is actually made more difficult to understand by the fact that Views actually includes a few relationships by default, and doesn't tell you they're there. For historical reasons, it would be inconvenient to remove these default relationships. When relationships are present, all fields (including relationships) will gain a new form item to let you select which relationship they will use. They will default to using no relationship at all.

The main example of the relationship that is there by default is the node --> user relationship; every node has an author, and if a node is in the query, the user who wrote that node is automatically made available. [Note: the author considers it an error that this relationship is automatic, but by the time it was realized this was in error, it was too late to change it.]

A similar relationship that is not automatically made available is for node revisions. Each revision has its own author, which is the user who made the revision. By adding the "Node revision: User" relationship, all of the 'user' fields, sorts, filters and arguments available to a user will now be available for the revision author.

When a relationship is added to the view, all applicable items will gain a "Relationship" select box, where you can choose which version of that particular item you wish to use. This can be illustrated with an example:

A 'comment' view contains the relationships 'Comment: node' and 'Comment: user'. This means that all the fields for the node that a comment is attached to are available, and all the user fields for that node author also become available. The other relationship makes fields for the author of the comment available -- very often not the author of the node!

When you add the "User: name" field, you will be presented with a select box. Either the node relationship or the user relationship must be selected, because there are two possible user names in the view to choose from.

Another example of relationships involves the Files table. In Drupal, files are related to users, but files are not necessarily related to nodes. However, the upload.module allows some files to be attached to nodes. The only way for Views to deal with this discrepancy is with relationships. When creating a 'node' view, it's possible to add an uploaded files relationship to get file data for nodes that were attached with the upload module. It is also possible to go the other way; from a files view you may add a relationship via the Upload table to view information about the node.

Page 28: Drupal: Views Module Guide

28

Sorts

Sort criteria determine what order the records are retrieved from the database and displayed in; generally, all you need to do is pick a field and choose ascending (1, 2, 3, 4) or descending (4, 3, 2, 1) and it will be done. If you have multiple sort criteria, the second (and later) items only come into play if the first item is the same.

Different data types sort just a little bit differently from others:

Number fields Number fields sort like you would expect. 1 comes before 2 which comes before 10 which comes before 100 which comes before 200, etc.

Text fields Text fields always sort alphabetically, even if the text contains numbers. This can have some odd effects if you have numbers stored in text, because the values 1, 3, 7, 10, 12, 20, 100, 120 will sort like this:

• 1 • 10 • 100 • 12 • 120 • 200 • 3 • 7

This is because these fields sort purely by characters, and not numeric value. i.e, comparing 200 and 3, the '2' comes before the '3', therefore, '200' is "smaller" than '3'.

Date fields Date fields often can have a 'granularity', which is a way of making similar dates actually be the same date. Take two dates that are close to each other: May 1, 2007 5:30 am and May 1, 2007 9:45am. Without granularity, the two dates are compared and the first date comes before the second date. However, if the granularity is set to 'day' it only looks at the parts of the date up to the day: May 1, 2007 and May 1, 2007. At that point, they are the same, and the sort would move on to the next sort criterion.

Page 29: Drupal: Views Module Guide

29

Displays

Displays tell Views where the output should go. By adding a display to a View, you can have your view appear as a page, or as a block, or even as an attachment to a different display on the view.

Each display can have its own settings, but when it's created, a display will take all of its basic settings from the default display which all Views must have. For most settings, there is an override button that will override that single setting for the current display. Overridden settings will have a mark in the summary for that display.

Please keep in mind that when you are editing a setting on a display that is not overridden, then by default you are editing that for all displays.

For fields, arguments, sorts, filters and relationships, you can only override all of them or none of them. To do this, click on the header for the filters or the rearrange button. Once you override, the display will then have its own copies of the fields/filters/etc and changes to the defaults will not be reflected on your display.

• Default display • Page display • Block display • Attachment display • Feed display

Page 30: Drupal: Views Module Guide

30

Default display

The default display is primarily a display to store settings, and isn't actually used anywhere within the Views system. It is possible for external programs to use the default display, but if they do they will (hopefully) tell you which display they will be working with. The default display is also a convenient display to use to embed into your site using PHP snippets; this is useful, for example, in node content, but this is something that should generally only be done by administrators.

In general, you probably want to add either a page display or a block display.

Page 31: Drupal: Views Module Guide

31

Page display

Page displays have a path and an optional menu component. Page displays will be the primary content for the page, meaning they will be displayed in the main content area when you visit the URL that corresponds to the path.

Page displays take their arguments from the URL. You can embed arguments into the URL using %; in previous versions of Views, this was '$arg'. For example, 'node/%/foo' will accept URLs such as 'node/1/foo'.

Page 32: Drupal: Views Module Guide

32

Block display

Block displays will show up on your blocks administration page. Once a block display is created and saved, it can be enabled and positioned in your theme by visiting administer >> site building >> blocks and selecting it from the list.

Blocks do not accept arguments from any source; the only way to get arguments to a block is to provide defaults to it, possibly via the PHP Code default setting.

• Edit the argument in question; you may want to override this argument if you have multiple displays using it.

• Change the "Action to take if argument is not present" to "Provide default argument". This will bring up a new box called "Provide default argument options".

• The most common default argument type used for blocks is Node from URL, where it attempts to determine if the URL refers to a node, for example if visiting 'node/1' or 'node/1/edit'. User ID from URL is also very common.

• If you change the default argument type to 'PHP Code' (note: You must have permission to use PHP code on your site) you can enter PHP to define the argument needed. Simply return the argument.

Page 33: Drupal: Views Module Guide

33

Attachment display

Attachment displays are 'attached' to another display in the same view. When the display is visited, the attached display will also be rendered and may be placed before, after or both before and after the original display. Attachment displays are often useful for displaying an argument summary view along with a page display that accepts arguments. This can be used to provide a kind of glossary.

Page 34: Drupal: Views Module Guide

34

Feed display

A feed display allows you to attach an RSS feed to a view.

Page 35: Drupal: Views Module Guide

35

Output styles (View styles)

The Views' style system is how you customize the output produced by your view. A view style is basically a smart theme template that processes the view data and then outputs it. All styles in Views can be overridden by placing copies of the templates in your theme directory and then modifying them. See the theme: information link available on all views to get hints for which templates a given view is using.

A breakdown of View output

By default, the style is unformatted, which means that there is very little style actually used; the records are simply displayed one after another, enclosed in a <div> tag so that you can use CSS to manipulate the view.

Some styles use a separate row style to determine how each row of the View looks. This is useful for mixing and matching styles to more readily produce exactly the kind of output you need.

Many styles can be grouped. For styles that can, there will be a 'grouping field' option; pick one of the fields to group by. This grouping field will be displayed as a header, and all rows will be displayed beneath it.

Each style is its own entity.

• Unformatted output style • Grid output style • RSS output style • Table output style • List output style • List summary style • Unformatted summary style • View row styles

o Comment RSS item row style o Fields row style o Node RSS item row style o Node row style

Page 36: Drupal: Views Module Guide

36

Unformatted output style

The unformatted output style simply places each row of the view, one after another, with no additional formatting.

Page 37: Drupal: Views Module Guide

37

Grid output style

The grid style will display each row of your view within a grid. You may customize the number of columns, though it defaults to 4. A grid looks like this:

row 1 row 2 row 3 row 4

row 5 row 6 row 7 row 8

row 9 row 10 row 11 row 12

row 13 row 14 row 15 row 16

The above uses the 'horizontal' alignment, where rows are added into the grid from left to right.

With a vertical alignment, rows will be placed from top to bottom, like this:

row 1 row 5 row 9 row 13

row 2 row 6 row 10 row 14

row 3 row 7 row 11 row 15

row 4 row 8 row 12 row 16

This style uses a row style to determine what each row will look like.

Page 38: Drupal: Views Module Guide

38

RSS output style

The RSS output style is only available for Feed display types. It will display the view as an RSS feed, which is a specialized XML output. This output is not user visible, but can be parsed by feed readers for aggregation.

You may supply a description for the RSS feed; most feed readers will display this description along with the contents of the feed. You may also select to use the site's mission statement for the description.

Page 39: Drupal: Views Module Guide

39

Table output style

The table style will display the View results as a table; each row of the table will correspond to a row from the view result.

When setting the table options, each field in the view will be presented with some information next to each field:

Column By default, each field is its own column. However, you can place multiple fields in the same column. To do this, pick which field you want to represent the column, then pick another field and set the 'column' value to that field. You can place as many fields as you like in a single column, but only the main field in a column can be click-sorted.

Separator If you have multiple fields in the same column, the separator will be placed between each one. At the very least, &nbsp; should be used, as without the separator the fields will be placed very close to each other. Common separators are a bullet, the | symbol, and a comma. If there are no other fields in the column, the separator will have no effect.

Sortable If checked, the header for the column will be clickable, and the user may re-sort the table by clicking on this to sort by that field. At this time Views does not support click-sorting to sort by multiple columns at the same time.

Default sort You may select a column which will be sorted by default when the table is first viewed. This column will be highlighted to the user. You may also select whether the default sort is ascending or descending.

Page 40: Drupal: Views Module Guide

40

List output style

The List view style will display every row of the view as part of an HTML list construct. For example:

• Row 1 • Row 2 • Row 3 • Row 4

You may select whether or not the list is ordered which just means whether or not it uses numbers instead of the bullet:

1. Row 1 2. Row 2 3. Row 3 4. Row 4

The list style also uses a row style which means that it doesn't care what the actual output for each row of the view is.

If you need information about using CSS to style list views, you may find this A list apart guide to styling lists useful.

Page 41: Drupal: Views Module Guide

41

List summary style

The list summary style is only available for summary styles, which are when an argument has been set to provide a summary if it was not provided with a value. This summary provides a list of possible candidates for the argument in a standard HTML list. Like the normal list style, you may set this list to be ordered or not.

You can also elect to display the number of matching records for the argument, plus change the number of items per page for the summary. This is often useful because summary views are often quite small, but other views quite space intensive. It is very common to have far more records available in the summary view than in the more normal view.

Page 42: Drupal: Views Module Guide

42

Unformatted summary style

The unformatted summary style is only available for summary styles, which are when an argument has been set to provide a summary if it was not provided with a value. This summary provides the possible candidates for the argument one after another with no special formatting. If inline is selected, the summary items will be enclosed within <span> tags. Otherwise the items will be in <div> tags.

You can also elect to display the number of matching records for the argument, plus change the number of items per page for the summary. This is often useful because summary views are often quite small, but other views quite space intensive. It is very common to have far more records available in the summary view than in the more normal view.

Page 43: Drupal: Views Module Guide

43

View row styles

A row style is an individual style to display only an individual record within a view. For example, a node type view would display one node per row; a user type view would display one user per row.

Some row styles use fields which means you select from the available fields to display; others do not; they are able to use the base type and create a display. Usually, row styles that do not use fields produce less efficient (slower) views, so bear this in mind when contemplating the performance of your site.

• Comment RSS item row style • Fields row style • Node RSS item row style • Node row style

Page 44: Drupal: Views Module Guide

44

Comment RSS item row style

This row style is only available to RSS styles. It produces XML necessary for an RSS feed for the comment.

Page 45: Drupal: Views Module Guide

45

Fields row style

The fields row style displays each field defined in the view, one after another. Each field defines its own output.

By default, each field is put in a <div> unless it is selected to be inline. If it is inline, it is put in a <span>. Two items in <div>s will be displayed one after another, with the second one below the first. Two items in <span>s will be displayed on the same line. One item in a <span> next to <div>s is the same as two items in <div>s. This means that for the inline setting to do anything, at least two consecutive items must be set inline.

You may define a separator which will be placed between each item. This separator may be html. You can use &nbsp; to print blank space.

Page 46: Drupal: Views Module Guide

46

Node RSS item row style

This row style is only available to RSS styles. It produces XML necessary for an RSS feed for the node record.

Page 47: Drupal: Views Module Guide

47

Node row style

The node row style will display each item of the view through Drupal's standard node_view() function. Views has very little control over this output, except for the options you see. Instead, the output is run through the standard node template mechanism (typically node.tpl.php or a variant thereof) and any decisions about what is output may be done there.

Views does add an extra 'suggestion' to the list of possible node templates: node-view-VIEWNAME.tpl.php -- you may use this to theme a node specifically for the view. This can be handy for creating very small teasers and the like.

You may opt to display the full node body or the node teaser, and you may add the node links (such as he 'comment' links that appear after a node) or not.

Because of this behavior, the node row style does not utilize fields and the Fields section will not be displayed.

Please note that this row style performs a node_load() for every row, and as such can produce a lot of extra queries. Sometimes this is necessary, but it can have a negative impact on your site's performance!

Page 48: Drupal: Views Module Guide

48

Embedding a view into other parts of your site

You can easily embed the results of a view into other parts of your site; either with code as a module, or in nodes or blocks as snippets.

The easiest way is to use the function views_embed_view():

/** * Embed a view using a PHP snippet. * * This function is meant to be called from PHP snippets, should one wish to * embed a view in a node or something. It's meant to provide the simplest * solution and doesn't really offer a lot of options, but breaking the function * apart is pretty easy, and this provides a worthwhile guide to doing so. * * @param $name * The name of the view to embed. * @param $display_id * The display id to embed. If unsure, use 'default', as it will always be * valid. But things like 'page' or 'block' should work here. * @param ... * Any additional parameters will be passed as arguments. */ function views_embed_view($name, $display_id = 'default') {

To figure out the id of a display, hover your mouse over the tab to select that display. Everything after the '#views-tab-' is the id of that display. This ID is guaranteed never to change unless you delete the display and create a new one.

Page 49: Drupal: Views Module Guide

49

Menu options (page display)

Page displays can hook into the Drupal menu system and provide menu links that will appear in the Navigation system as well as tabs that can be used to keep Views next to each other.

For simple menu links, there is very little you need to do; simply select 'Normal menu entry' and fill in the text for the title. This will appear in the Navigation menu by default; you will need to visit the menu administration page to move this to another menu.

Tabs are not quite so simple; there are some complex rules for using tabs in Drupal.

1. All tabs must have a parent, which is the next level up in the path hierarchy. For example, if the view path is 'example/taba' then the parent must be 'example'.

2. All tabs must have one and only one default tab; this is usually the same content as the parent. 3. If a parent does not exist, when creating the 'default' tab, Views will allow you to also create a

parent item. It will automatically set up the URL for you when it does this. 4. Tab weight is used to control what order the tabs are displayed in. Lower numbers will display

more to the left. For tabs whose numbers are the same, they will be displayed alphabetically. 5. Drupal only supports 2 levels of tabs, so be careful about trying to put tabs within tabs within

tabs. That won't work.

For example, if you have two views that you want to be tabs, you could set it up like this:

• In the first view, set the path to 'tabs/tab1'. Set it to be the 'default tab', set the title to 'Tab 1' and the weight to 0.

• Click update and you will be taken to a form that lets you define the parent. Since 'tabs' doesn't already exist in the system, select 'Normal menu item', and set the title to 'Tabs'.

• On the second view, set the path to 'tabs/tab2'; set it to be a 'Menu tab', and set the title to 'Tab 2'.

With this done, you will now have a Navigation link named 'Tabs' and when you click on it, you will go to the tabs, with 'Tab 1' being the default tab that appears. You can then click between Tab 1 and Tab 2.

Page 50: Drupal: Views Module Guide

50

Path options (page display)

If a display has a path that means that it can be retrieved directly by calling a URL as a first class page on your Drupal site. Any items after the path will be passed into the view as arguments. For example, if the path is foo/bar and a user visits http://www.example.com/foo/bar/baz/beta, 'baz' and 'beta' will be given as arguments to the view. These can be handled by adding items to the arguments section.

You may also use placeholders in your path to represent arguments that come in the middle. For example, the path node/%/someview would expect the first argument to be the second part of the path. For example, node/21/someview would have an argument of '21'.

Note: Views 1 used $arg for this kind of thing. $arg is no longer allowed as part of the path. You must use % instead.

If multiple displays within the same view have the same path, the user will get the first display they have access to. This means you can create successfuly less restricted displays in order to give administrators and privileged users different content at the same path.

Page 51: Drupal: Views Module Guide

51

Theme information

You may use any of the following possible theme files to modify individual parts of your view. In total, there are four parts to theming a view.

• The display theme is usually views-view.tpl.php and it largely controls the decorations around a view; where the header, footer, pager, more link, feed icon, etc, will be placed.

• The style will control how all of the results of the display are put together. It may be as simple as just displaying all of the rows, or it may be a complex table generator or something in between.

• The row style controls each individual row; not all styles utilize the row style (notably the table), but most others do.

• Finally, field themes allow you to override the look and even the data of each individual field, if the style uses fields. The actual template the system will use should be hilighted in bold.

A breakdown of View output

The link to the left of each type will give you information about the default template used for that type. You may cut and paste this and place it in your theme with the appropriate template, or you may copy the base file from the views/theme directory (or, if provided by a module, from the module's directory). It is important that you clear the theme registry cache every time you add a new template, or the new template will not be picked up.

Important note: You place your custom template files in your theme directory, not views/theme. This is always true of theming with Drupal.

In addition to this tool, the very useful devel module contains a tool called the "Theme developer" which does a good job of visually showing you which areas of your site use which themes. Be careful with it, though, as the theme developer causes the Views edit page to break.

Also, this feature will only work properly with Drupal 6.3 and later; prior to Drupal 6.3 this patch will be required.

• Using CSS with Views • Using Views templates

Page 52: Drupal: Views Module Guide

52

Using CSS with Views

Views uses a wide array of CSS classes on all of its content to ensure that you can easily and accurately select exactly the content you need in order to manipulate it with CSS.

Typically, every view is wrapped in a div with the name of the view as part of its class (for all these examples, we will assume the name of the view is myview), as well as the generic class 'view':

<div class="view view-myview"> ... </div>

In your CSS, you can modify all views:

div.view { border: 1px solid black; }

Or just your view:

div.view-myview { background: yellow; }

By default, the general view template also provides the following classes to easily style other areas of the view:

• .view-header • .view-filters • .view-content • .view-empty (if an "empty" text is used when the view has no results) • .view-footer • .feed-icon • .attachment-before (if using an "attachment" display) • .attachment-after (if using an "attachment" display)

So for example:

div.view-myview div.view-header { /* make the header stand out */ font-size: 120%; font-weight: bold; } div.view-myview div.view-footer { /* Make the footer less important */ font-size: 80%; font-style: italic; color: #CCC; }

In the above example, we whimsically made the header bold and in a bigger font, and the footer smaller, italicized, and greyish.

Views with fields

If your view has fields, each field is uniquely tagged with its ID. A field's ID may be gleaned from the Theme: Information page. Note that due to CSS rules, any _ in the id will be converted to - automatically, so if you have a field whose id is 'edit_node' (this is the field used to provide an "edit" link to a node), it will be 'edit-node'. Additionally, to make sure that the view IDs don't conflict with other css

Page 53: Drupal: Views Module Guide

53

classes in the system, they will be pretended with 'views-field-'; thus, the final CSS class for the field with the id 'edit_node' will be views-field-edit-node.

Exactly how this appears is going to depend upon the style you're using. For example, the 'unformatted' style uses div.views-field-edit-node and div.views-label-edit-node to access that particular field, but a table would use td.views-field-edit-node and th.views-field-edit-node to access the table header; or just .views-field-edit-node to affect both.

.view-myview th { color: red; /* make all headers red */ } .view-myview .views-field-title { font-weight: bold; /* Make the 'title' field bold */ } .view-myview td.views-field-body { font-size: 60%; /* Make the text in the body field small */ }

Page 54: Drupal: Views Module Guide

54

Using Views templates

Views theme templates are straightforward to use with the Drupal theming system. If you are unfamiliar with the theming system at all, you should probably at least read drupal.org theming documentation. That said, these are the important things you need to know:

1. Copy a base Views template to one of the names provided from the Theme: Information section of the View. Copy this template right into your theme directory.

2. Clear the theme registry. See the instructions for how to do this. 3. Your new template should now operate; assuming you picked a nicely named template that

includes the view name, that template should now be active for your view. A good example is views-view-list--foobar.tpl.php which would work for a view named 'foobar'.

4. You can now modify this template all you like.

For any template that uses fields, the fields will be in array. In order to use this effectively, you will need to understand enough PHP to fetch data from an array. This is a place where the devel module can really help you, because you can use its dsm() function right in your template to see what variables it uses. There is an alternative to dsm() that works without devel module, but it's a bit longer to use.

For example, I placed the following code inside a loop in views-view-table.php.php: <?php drupal_set_message('<pre>' . var_export($row, true) . '</pre>'); ?>

And it produced this output: array ( 'nid' => '97', 'title' => 'Scisco Ideo Vicis Feugiat Qui', 'name' => 'luwrepuslan', )

My view had three fields: Node: Nid Node: Title User: Name

The contents of the $row variable included these fields, in precisely the order that I had arranged them to using the Views rearrange link. Also worth noting, though, is that each field also has an identifier so it can easily be pulled out of the row should I want to display it differently. Using <?php print $row['title']; ?>

Would print just the title for that row. Please remember that I'm doing this inside the loop, so this will get repeated for every row of the view.

The IDs used to fetch items from the array, id $row['title'] can be quickly and easily looked up on the Theme: Information page. Once a field has been added to the view, its ID will not change, but note that if there are two "title" fields in a view, one will be 'title' and the other will be 'title1', in order to prevent namespace collisions.

The important thing here is that Views does provide IDs. Views doesn't tell you what these IDs are, but it's easy to get them by dumping the row data and doing a simple visual inspection. Views does guarantee that these IDs will not change, unless you actually add a new field and remove the existing one (in which case 'title', above, would become 'title1').

The basic fields template

The most common template people will need to rewrite is the "simple" views-view-fields.tpl.php, which is the template used by the Fields row style and all it does is display a simple list of fields. However, it is not that simple to the user. Because the template can't inherently know what the fields are, it has to go through an array in a loop.

Page 55: Drupal: Views Module Guide

55

This loop isn't very handy when you really want to have fine control over the template by placing your fields precisely where and how you want. Relax, though; if you know what your fields are, you can rewrite this. If you end up writing your own HTML, the only part that is really important is the content for each field. We know from above that you can get the ID for each field on the Theme: Information page from the view. In the header for the template, we can see that the fields are all in the $fields array, and each field is an object. That leads us to this:

<?php print $fields['some_id']->content; ?>

Assuming you replace some_id with an id found on the theme: information page, this code will print the content for that field. You can also get the label and some other data about the field, as well as the raw information. Complete details for what is available are documented directly in views-view-fields.tpl.php.

Keep in mind that if you rewrite your templates using this, you'll need to maintain this template whenever changes are made to the fields of the view; while this isn't generally recommend, sometimes it's necessary to get the kind of control you might ultimately need.

Page 56: Drupal: Views Module Guide

56

Updating your views from Views 1 to Views 2

TODO: This document needs to be fleshed out.

Page 57: Drupal: Views Module Guide

57

View types

The view type describes how this view is stored; Views is capable of having Views entirely in code that are not in the database. This allows modules to easily ship with Views built in, and it allows you to create a module to store your views for easy deployment between development and production servers.

Normal Normal views are stored in your database and are completely local to your system.

Default Default views are stored only in code and are not anywhere in your database. They may be enabled or disabled but you may not completely remove them from your system. You can override the view which will create a local copy of your view. If you do this, future updates to the version in code will not affect your view.

Overridden Overridden views are stored both in code and in the database; while overridden, the version that is in code is completely dormant. If you revert the view, the version in the database will be deleted, and the version that is in code will once again be used.

You may store your views in code with the following procedure:

1. Create a module to store the views. 2. Add the function MODULENAME_views_default_views() to this module. 3. Export the view you wish to store in your module in code. Cut and paste that into the

abovenamed function. Make sure the last line of the view is: $views[$view->name] = $view; 4. Make sure the last line of the function is return $views; 5. After you make any changes, be sure to clear the Views' cache. You may do this from the

Tools menu.

Page 58: Drupal: Views Module Guide

58

What are overrides?

If an item is using defaults then it is using values from the default display. IMPORTANT NOTE: If you modify this value, you are modifying the default display and thus modifying for all displays that are using default values.

If that is not what you intend, you must click the override button. Once overridden, that display now has its own version of the value; modifying it will not modify it for other displays.

For Relationships, arguments, fields, sort criteria, and filters, each of these must be overridden as a group! In other words, you cannot override a single filter, but instead must override allr filters. A message will appear on the item to let you know what its status is, but you can only change the status by clicking on the header or the rearrange button for that item.

Page 59: Drupal: Views Module Guide

59

Views' API

Views allows modules to describe their tables relationships to each other, as well as fields, filters, sort criteria and arguments via hook_views_data(). Whenever Views deems it necessary, this hook is called, the data aggregated together and cached. hook_views_data_alter() may also be used to modify existing data, changing other module's handlers or adding handlers to other module's tables.

Views also allows modules to create new display types, style types, row styles, argument default handlers and argument validators via hook_views_handlers() and hook_views_plugins().

These hooks are kept in a file named MODULENAME.views.inc. This file is automatically included upon need, so there is no need to try and include this in hook_init or any other method of including .inc files. This file should store hook_views_data, hook_views_data_alter(), hook_views_plugins(), hook_views_handlers(), as well as any other hooks and subsidiary data that will only be used by your module when Views is active. All handlers and plugins provided by your module should be in separate .inc files.

There are two similar files, MODULENAME.views_default.inc and MODULENAME.views_convert.inc which contain default views and views 1 to views 2 convert helpers, respectively.

hook_views_api()

In order for your files to be included, your module must first implement hook_views_api() in the main .module file. This module should return array of information. The following items may be returned:

api This must appear; it should be the oldest API version that your module can work with. If Views is currently running an older version of the API, it will ignore your module's views integration. This is a good thing, as it will prevent code crashes, at the expense of your module's functionality disappearing. You may find the current Views API version by calling views_api_version() which is implemented at the top of views.module. This version numbering starts at 2.0. Every time changes are made to the Views handlers and plugins or other aspects of the Views API, the number will tick up (by either .001, .01 .1 or 1 depending upon how major the changes are). Note that views_api_version() was introduced in Views 2.0-rc2 and may not exist prior to that version. You may use function_exists() to test to see if this function is there. Often these versions are basically compatible with each other and Views won't care if your module implements 2.000, 2.001, 2.002, etc. Your module can request that it won't work with any version older than a given version, however. Views will determine, itself, if a newer version will work.

path If your *.views*.inc files are not in the same directory as the .module file, then return the full path here. You should probably use something like drupal_get_path('module', 'yourmodulename') . '/includepath'.

• Describing tables to Views • Using default views in your module • How Views handlers work • How Views plugins work • Upgrading your module Views 1 to Views 2 • Integrating the Node Example module

Page 60: Drupal: Views Module Guide

60

Describing tables to Views

Tables are described to Views via hook_views_data(), which returns an array of table information, keyed by the name of the table. For example, if your module is describing three tables, 'foo', 'bar' and 'baz', your array will look like this:

$data = array( 'foo' => array( // ...info here... ), 'bar' => array( // ...info here... ), 'baz' => array( // ...info here... ), );

The key should be the actual database name of the table (not including prefix), but it can be an alias as long as the join information (explained later) contains the real name of the table.

Each item in the array should be a field in the table, with the exception of a special information section called 'table'. Example:

$data['foo'] = array( 'table' => array( // ... info about the table, described later ... ), 'bar' => array( // ... info about the field named 'bar', i.e, foo.bar, ), 'baz' => array( // ... info about the field named 'baz', i.e, foo.baz, ), );

Once you get down to an array that contains actual data, that piece of the array will often be referred to as the definition.

The 'table' section

Each table should have a 'table' section in it, which is used to set default information for the table, such as the group, as well as the very important joins and whether or not this is a base table.

First, there are several items that are actually for fields but can be placed here so that all fields within the table inherit them:

group The name of the group this item will be with. In the UI, this is displayed as Group: Title. For example, "Node: Node ID", "Taxonomy: Term description", etc. It is important to be consistent with groups, because the UI sorts by group, and allows filtering by group to find fields as well.

title The actual name of the field; it should be concise and descriptive.

help A longer description to help describe what the field is or does. It should try to be only a line or two so as not to clutter the UI.

In general, having 'title' and 'help' at the table level doesn't make a lot of sense, but usually every item in a table is in the same group. Thus it is very common to define the 'group':

$data['foo']['table']['group'] = t('Foo');

Page 61: Drupal: Views Module Guide

61

Base table

If your table is a base table -- meaning it can be the primary, central table for a View to use, you can declare it to be a base table. This primarily provides UI information so that it can be selected. For example:

// Advertise this table as a possible base table $data['node']['table']['base'] = array( 'field' => 'nid', 'title' => t('Node'), 'help' => t("Nodes are a Drupal site's primary content."), 'weight' => -10, );

The following tags are available in the

field The primary key field for this table. For Views to treat any table as a base table, it must have a primary field. For node this is the 'nid', for users this is the 'uid', etc. Without a single primary key field (i.e. not a composite key), Views will not be able to utilize the table as a base table. If your table does not have a primary key field, it is not too difficult to just add a serial field to it, usually.

title The title of this table in the UI. It should be singular and describe the object that this table contains from the perspective of the user.

help A short piece of text to describe what object this table contains.

database If this table is held in a different database from your Drupal database, specify it as a string in the exact same format as the settings.php file. This is a special purpose variable that will probably be only used in site specific code, and it must be the same database type as your Drupal database. Also, don't try to join it to any table that isn't in the same database. That'll just create all kinds of silly errors. For example: // In settings.php for your site // Your drupal (site) database needs to be called 'default' $db_url['default'] = 'mysqli://user:pass@host/drupal_db'; $db_url['budget'] = 'mysqli://user:pass@host/other_db';

Then when you are describing the external database in your base table you would write something like this:

$data[$table]['table']['base'] = array( 'field' => 'Primary key', 'title' => t('Field name'), 'help' => t('Field description'), 'database' => 'budget', 'weight' => -10, );

Linking your table to existing base tables

For Views to use your table, it has to either be a base table, or know how to link to an existing base table. Or sometimes both. Views uses this information to create a path to the base table; when the table is added to the query, Views will walk along this path, adding all tables required into the query.

How term_data joins to node

Page 62: Drupal: Views Module Guide

62

In the above example, to use these with 'node' as the base table, both 'term_data' and 'term_node' need to be defined, and they each need a join handler for node:

$data['term_data']['table']['join']['node'] = array( 'left_table' => 'term_node', 'left_field' => 'tid', 'field' => 'tid', );

The above can be read as "In order to join to the node table, the term_data table must first link to the term_node table, and they join on the 'tid' field.". When adding this table to the query for a node view, Views will look at this and then look for the term_node table.

$data['term_node']['table']['join']['node'] = array( 'left_field' => 'nid', 'field' => 'nid', );

Above, the fact that 'left_table' is left out lets us know that term_node links directly to the node table, using the 'nid' field on both sides of the join.

Quite a few more fields are available in this definition:

handler The name of the handler object to use. Defaults to 'views_join'. You may create custom join handlers that may or may not use any of the data below, as they see fit.

table Table to join. This is optional, and should only be used if the table being referenced is an alias.

field Field to join on. This is required.

left_table The next step toward the final destination. If this is the final destination it may be omitted.

left_field The field to join to on the left side. This is required.

type Either LEFT (default) or INNER.

extra Either a string that's directly added, or an array of items. Each item is, itself, an array: field Field or formula operator Similar to filters, this is the operator, such as >, <, =, etc. Defaults to = or IN. value Must be set. If an array, operator will be defaulted to IN. numeric If true, the value will not be surrounded in quotes, and %d will be used for its placeholder. extra type How all the extras will be combined. Either AND or OR. Defaults to AND.

Describing fields on tables

Aside from the special table tag, each table can also have an unlimited number of field designations; these correspond roughly to fields on the table, though it is very common to use non-fields to display data that isn't directly in a field, such as data arrived from formulae, or special links related to the object the table is part of.

Each field is described in the view data with an array, keyed to the database name of the field. This array may contain some information fields, plus an entry in each of the five types of items Views has per field: argument, field, filter, relationship, sort. For example:

Page 63: Drupal: Views Module Guide

63

$data['node']['nid'] = array( 'title' => t('Nid'), 'help' => t('The node ID of the node.'), // The help that appears on the UI, // Information for displaying the nid 'field' => array( 'handler' => 'views_handler_field_node', 'click sortable' => TRUE, ), // Information for accepting a nid as an argument 'argument' => array( 'handler' => 'views_handler_argument_node_nid', 'name field' => 'title', // the field to display in the summary. 'numeric' => TRUE, 'validate type' => 'nid', ), // Information for accepting a nid as a filter 'filter' => array( 'handler' => 'views_handler_filter_numeric', ), // Information for sorting on a nid. 'sort' => array( 'handler' => 'views_handler_sort', ), );

The above example describes the 'nid' field on the 'node' table, providing 4 of the 5 handlers. Note that while field is normally expected to be the database name of the field, it doesn't have to be; you can use an alias (which is how you get multiple handlers per field) or something completely made up for items that aren't tied to the database. For example:

$data['node']['edit_node'] = array( 'field' => array( 'title' => t('Edit link'), 'help' => t('Provide a simple link to edit the node.'), 'handler' => 'views_handler_field_node_link_edit', ), );

The above handler definition an edit link to a node, but this isn't a field in and of itself. For aliased fields, here is another example:

$data['users']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', ), );

The above definition provides an alternate filter handler on the uid field for the current user.

The following items are allowed in the field definition:

group, title, help As above, these fields are for the UI. If placed here, any of these fields will override a setting on the base table.

real field If this field is an alias, the "real field" may be placed here, and the handler will never know the difference.

field

Page 64: Drupal: Views Module Guide

64

A handler definition for the "Field" section, which is a field that may be displayed in a view. The definition is an array; the contents of the array are completely up to the handler, other than the 'handler' definition. If omitted, handler will default to 'views_handler_field'.

filter A handler definition for the "Filters" section, which will be used to apply WHERE clauses to the view. The definition is an array; the contents of the array are completely up to the handler, other than the 'handler' definition. If omitted, handler will default to 'views_handler_filter'.

sort A handler definition for the "Sort criteria" section, which will be used to add an ORDER BY clause to the view. The definition is an array; the contents of the array are completely up to the handler, other than the 'handler' definition. If omitted, handler will default to 'views_handler_sort'.

relationship A handler definition for the "Field" section, which is a way to bring in new or alternative base tables in the view. The definition is an array; the contents of the array are completely up to the handler, other than the 'handler' definition. If omitted, handler will default to 'views_handler_relationship'. The basic relationship handler requires 'base' and 'base field' to be set; 'base' and 'base field' represent the "right" half of the join that will use this field as the left side.

argument A handler definition for the "Field" section, which is method of accepting user input from the URL or some other source. The definition is an array; the contents of the array are completely up to the handler, other than the 'handler' definition. If omitted, handler will default to 'views_handler_argument'.

For more information about what handlers need/use what data, visit the Views API site and check out the available handlers.

Page 65: Drupal: Views Module Guide

65

Using default views in your module

Views can be stored in the database, which is typical of smaller sites and hobby sites. However, Views may also be stored directly in the code as "default" views, (which simply means they're available by default). Modules often come with views that are specific to the module data, but it's also possible -- and highly recommended -- that sites which have separate "development" and "production" sites export their views into default views in a site-specific module. This makes it very easy to transfer views from dev to production without making database changes.

Creating a module

First, create a directory in sites/all/modules for your new module. Call it whatever you like, but for this example we will call it mymodule.

In this directory, create a mymodule.module file. It can be empty for now, but it should at least contain an opening PHP tag:

<?php // $Id $

It should not contain a closing ?> tag, as the closing ?> tag is not required and anything AFTER the closing tag, such as a space or a linefeed, will be displayed directly to the browser and can potentially cause problems.

The .module file will contain functions and drupal hooks. Hooks are specially named functions that Drupal will call in order to get your module's response at certain times while generating pages. The only function you will need for this exercise is the 'views_api' hook that tells Views that this module supports the Views API and what version:

function mymodule_views_api() { return array('api' => 2.0); }

For other uses you may well add additional functions.

Second, you need to create a mymodule.info file:

; $Id $ name = My module description = My site specific module. core = 6.x

Once you have these two files set up, you should be able to activate your new module at the Administer >> Site building >> Modules page.

Exporting your views

The easiest way to do this is to activate the 'views_export' module, and navigate to Administer >> Views >> Tools >> Bulk export Place a check next to each view that you want in your module, type the module name into the text field, and click export. This will create the entire hook_views_default_views() function for you.

You can also export individual views. If you do this, keep in mind that this export does not include the line that adds the exported $view into the larger $views array:

$views[$view->name] = $view

To place this into your hook_views_default_views() you will need to place that after the view, and make sure the function returns $views at the end.

Page 66: Drupal: Views Module Guide

66

Placing your exported views into your module

Cut and paste the entire output of the bulk export tool into mymodule.views_default.inc -- and be sure to put a <?php at the top of the file so that the webserver knows that it's PHP code! Then visit the Views tools page and clear the Views cache. Your views should now be listed as Overridden on the view list page. If you revert these views, they will be removed from the database, but will remain in code.

Theming your views in your module

You can theme these views in the module and not need to rely on the theme to do this at all; and in fact, the theme can continue to override these just like it ordinarily would, even if your module provides a theme. This is very useful for distributing a module where the view needs to look "just so."

To do this, you need to implement hook_theme() in your module:

function mymodule_theme($existing) { return array( 'views_view__viewname_displayid' => array ( 'arguments' => array('view' => NULL), 'template' => 'views-view--viewname--displayid', 'original hook' => 'views_view', ), ); }

There are a small number of gotchas in doing this that you must be aware of.

1. When referring to a template filename, you always use dashes in the name. i.e, views-view--viewname--displayid.tpl.php. However, when referring to the hook or function names, you use underscores instead of dashes. i.e, views_view and views_view__viewname_displayid

2. The 'arguments' change based upon which of the 3 types you're overriding. There's the 'display', the 'style' and the 'row' style. The above code is assuming the display, which is usually just views_view. Here are the possibilities:

display: array('view' => NULL), style: array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL), row style: array('view' => NULL, 'options' => NULL, 'row' => NULL),

Be sure to use the right arguments line or the theme system will not properly translate.

3. The 'template' line should never include the extension, so drop the .tpl.php from it.

4. You need to make sure that the Views preprocess functions get registered. The 'original hook' line in the definition does that, but it can only do it if it comes after the Views registration, which actually happens very late in theme building. 99% of the time, your module will come before Views. You have two choices to deal with this:

1. Set your module's weight to 11 or higher in the database. Views' weight is 10. You can make this happen automatically when the module is first installed by creating a mymodule.install file and using this code:

function mymodule_install() { db_query("UPDATE {system} SET weight = 11 WHERE name = 'mymodule'"); }

If you use this method, the original hook should be set to the name of the original template being used. i.e, if this is a variate of views-view-list.tpl.php, this should be 'views_view_list'.

Page 67: Drupal: Views Module Guide

67

2. You can also just force it to list the preprocessors without actually having to detect them. This doesn't require modifying your module's weight, which is not always possible, you can insert this code into the array:

'preprocess functions' => array( 'template_preprocess', 'template_preprocess_views_view', 'mymodule_preprocess_views_view__viewname_displayid', ),

The first one is the global 'template_preprocess' function which all templates utilize. It does some basic things such as setting up $zebra and a few other items. See api.drupal.org for specifics.

The second one is the plugin specific preprocess. Like 'original hook' it should conform to the name used by the original template. i.e, if the original template was views-view-list.tpl.php then that preprocess function would be named template_preprocess_views_view_list.

The third one is your module's preprocess function, if it needs one. In general, you probably will not need one, and you should only attempt to use one if you are reasonably familiar with the concept of preprocess functions and Drupal's theme system in general. See Drupal's theme documentation for more information.

Page 68: Drupal: Views Module Guide

68

How Views handlers work

In Views, a handler is an object that is part of the view and is part of the query building flow.

Handlers are objects; much of the time, the base handlers will work, but often you'll need to override the handler for something. One typical handler override will be views_handler_filter_operator_in which allows you to have a filter select from a list of options; you'll need to override this to provide your list.

Handlers have two distint code flows; the UI flow and the view building flow.

For the query flow:

handler->construct() Create the initial handler; at this time it is not yet attached to a view. It is here that you can set basic defaults if needed, but there will be no knowledge of the environment yet.

handler->set_definition() Set the data from hook_views_data() relevant to the handler.

handler->init() Attach the handler to a view, and usually provides the options from the display.

handler->pre_query() Run prior to the query() stage to do early processing.

handler->query() Do the bulk of the work this handler needs to do to add itself to the query.

Fields, being the only handlers concerned with output, also have an extended piece of the flow:

handler->pre_render() Called prior to the actual rendering, this allows handlers to query for extra data; the entire resultset is available here, and this is where items that have "multiple values" per record can do their extra query for all of the records available. There are several examples of this at work in the code.

handler->render() This does the actual work of rendering the field.

Most handlers are just extensions of existing classes with a few tweaks that are specific to the field in question. For example:

/** * Filter by node type */ class views_handler_filter_node_type extends views_handler_filter_in_operator { function get_value_options() { if (!isset($this->value_options)) { $this->value_title = t('Node type'); $types = node_get_types(); foreach ($types as $type => $info) { $options[$type] = $info->name; } $this->value_options = $options; } } }

views_handler_filter_in_operator provides a simple mechanism to set the list used and the rest of the handler is perfectly fine for this.

Handlers are stored in their own files; for these files to be loaded by Views on demand, they must first be registered. Since Views core handlers are also loaded this way, it's imperative that your module also implement this pattern in order to prevent code crashes when your handler's parent class is not yet available.

Page 69: Drupal: Views Module Guide

69

To register handlers, you must implement hook_views_handlers(). This hook returns an array with two keys; the first key is info which contains the modulename (which is only necessary if you're registering handlers on behalf of another module, such as what Views does) and path, which is the search path to find the files. This path is only necessary if your files will not be stored in the same directory as the .module file.

The other key is handlers which contains a full array of handlers and the information for each handler. The key to each handler array is the name of the handler class. It can contain:

parent The class that this handler extends. This is important to make sure that the parent class is included before your handler class. Without this, you may cause people's sites to crash in a difficult to recover state. Be sure you get this right!

file The filename the handler is in. By default, this will be classname.inc -- however, you can have multiple similar handlers together in one file. However, because there is only one parent, please be sure that the parentage on these handlers matches! Otherwise you will run into whitescreens as not all parents will be loaded.

You can see examples of this function in any of the various module.views.inc files in the views modules directory.

The best place to learn more about handlers and how they work is to explore the views API site and use existing handlers as a guide and a model. Understanding how views_handler and its child classes work is handy but you can do a lot just following these models. You can also explore the views module directory, particularly node.views.inc.

Please note that while all handler names in views are prefixed with views_, you should use your own module's name to prefix your handler names in order to ensure namespace safety. Note that the basic pattern for handler naming goes like this:

[module]_handler_[type]_[tablename]_[fieldname]. Sometimes table and fieldname are not appropriate, but something that resembles what the table/field would be can be used.

Page 70: Drupal: Views Module Guide

70

How Views plugins work

In Views, a plugin is a bit like a handler, but plugins are not directly responsible for building the query. Instead, they are objects that are used to display the view or make other modifications.

There are 6 types of plugins in Views:

Display Display plugins are responsible for controlling where a view lives. Page and block are the most common displays, as well as the ubiquitous 'default' display which is likely what will be embedded.

Style Style plugins control how a view is displayed. For the most part they are object wrappers around theme templates.

Row style Row styles handle each individual record from a node.

Argument default Argument default plugins allow pluggable ways of providing arguments for blocks. Views includes plugins to extract node and user IDs from the URL; additional plugins could be used for a wide variety of tasks.

Argument validator Validator plugins can ensure arguments are valid, and even do transformations on the arguments.

Access Access plugins are responsible for controlling access to the view.

Plugins are registered by implementing hook_views_plugins() in your modulename.views.inc file and returning an array of data.

The array will look something like this: return array( 'display' => array( // ... list of display plugins, ), 'style' => array( // ... list of style plugins, ), 'row' => array( // ... list of row style plugins, ), 'argument default' => array( // ... list of argument default plugins, ), 'argument validator' => array( // ... list of argument validator plugins, ), 'access' => array( // ... list of access plugins, ), );

Each plugin will be registered with an identifier for the plugin, plus a fairly lengthy list of items that can define how and where the plugin is used. Here is an example from Views core:

'node' => array( 'title' => t('Node'), 'help' => t('Display the node with standard node view.'), 'handler' => 'views_plugin_row_node_view', 'path' => drupal_get_path('module', 'views') . '/modules/node', // not necessary for most modules 'theme' => 'views_view_row_node',

Page 71: Drupal: Views Module Guide

71

'base' => array('node'), // only works with 'node' as base. 'uses options' => TRUE, 'type' => 'normal', ),

Of particular interest is the path directive, which works a little differently from handler registration; each plugin must define its own path, rather than relying on a global info for the paths. Also, there is an optional parent directive which is automatically filled in to be the base parent for the plugin type. Usually this is enough, but if your plugin derives from something other than the base, it must be filled in. For example:

'feed' => array( 'title' => t('Feed'), 'help' => t('Display the view as a feed, such as an RSS feed.'), 'handler' => 'views_plugin_display_feed', 'parent' => 'page', // so it knows to load the page plugin .inc file 'uses hook menu' => TRUE, 'use ajax' => FALSE, 'use pager' => FALSE, 'accept attachments' => FALSE, 'admin' => t('Feed'), 'help topic' => 'display-feed', ),

Note that unlike handler registration, where parentage is referred to by object name, with plugins it is referred to by the unique plugin identifier. Please be sure to prefix your plugin identifiers with your module name to ensure namespace safety; after all, two different modules could try to implement the 'grid2' plugin, and that would cause one plugin to completely fail.

...TODO: Finish this document....

Page 72: Drupal: Views Module Guide

72

Upgrading your module Views 1 to Views 2

Missing help topic.

Page 73: Drupal: Views Module Guide

73

Integrating the Node Example module

For the new table defined by the Node example module to be understood by the views module you need to create a node_example.views.inc file that describes the table and its relationships to the rest of the database. In order for views to know that this file is to be loaded you need to implement hook_views_api. This is done by adding the following function into your node_example.module file

<?php /** * Implementation of hook_views_api(). * * This tells drupal that there is Views integration file named * module-name.views.inc */ function node_example_views_api() { // Note that you can include 'path' in this array so that your views.inc // file can be stored in a different location. return array( 'api' => 2.0 ); } ?>

Below is the contents of a simple node_example.views.inc file that allows you to create views that include the new color and quantity information.

<?php // $Id: api-example.html,v 1.2 2009/09/15 15:44:14 merlinofchaos Exp $ /** * This file is used to tell the views module about the new node_example table. * * Database definition: * @code * CREATE TABLE node_example ( * vid int(10) unsigned NOT NULL default '0', * nid int(10) unsigned NOT NULL default '0', * color varchar(255) NOT NULL default '', * quantity int(10) unsigned NOT NULL default '0', * PRIMARY KEY (vid, nid), * KEY `node_example_nid` (nid) * ) * @endcode */ function node_example_views_data() { // Basic table information. // ---------------------------------------------------------------- // node_example table // New group within Views called 'Example' // The group will appear in the UI in the dropdown tha allows you // to narrow down which fields and filters are available. $data = array(); $data['node_example']['table']['group'] = t('Example'); // Let Views know that our example table joins to the 'node' // base table. This means it will be available when listing // nodes and automatically make its fields appear. // // We also show up for node revisions.

Page 74: Drupal: Views Module Guide

74

$data['node_example']['table']['join'] = array( 'node_revisions' => array( 'left_field' => 'vid', 'field' => 'vid', ), 'node' => array( 'left_field' => 'vid', 'field' => 'vid', ), ); // quantity $data['node_example']['quantity'] = array( 'title' => t('Quantity'), 'help' => t('Quantity of items.'), 'field' => array( 'handler' => 'views_handler_field_numeric', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', ), 'sort' => array( 'handler' => 'views_handler_sort', ), ); // Color $data['node_example']['color'] = array( 'title' => t('Color'), 'help' => t('Color of item.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), ); return $data; } ?>

Some notes on usage:

Within Views, click on the Add tab. You have a number of type options here. Normally you would select either 'Node' (if you only want to display information on current nodes) or 'Node revision' (if you want to display information on all revisions of the nodes)

With this configuration you always pull out of the database, data for every single node, whether or not it has color and quantity information. To display information on just those nodes that have color and quantity information you can use a filter so that only nodes which don't have a NULL color or a NULL quantity are displayed.

Page 75: Drupal: Views Module Guide

75

Type/relationship extension

When your tables have first class data, you will often need to have own View types and View relationships defined. With the current node_example table this isn't required although I try to justify it below on an efficiency basis. See [[http://groups.drupal.org/node/17236#comment-58980|this discussion]] as to why it isn't justified.

Pulling data out of the database for every node when you only want data for the new Example node type is inefficient. To reduce the initial data extraction to just that relating to the new Example nodes requires that you make the node_example table the base table. This can be done by adding the following code into the node_example.views.inc file just before the 'return $data;'

<?php // **** Begin optional extra for type and relationships **** // Use node_example as a new base table // by creating a new views type called 'Node example' // This allows it to be selected as the 'view type' // when you initially add a new view. $data['node_example']['table']['base'] = array( 'field' => 'vid', 'title' => t('Node example'), 'help' => t("Node example type with color and quantity information."), 'weight' => -9, ); // When using the new 'Node example' type you need to use relationships // to access fields in other tables. // Relationship to the 'Node revision' table $data['node_example']['vid'] = array( 'title' => t('Node revision'), 'help' => t('The particular node revision the color and quantity is attached to'), 'relationship' => array( 'label' => t('Node revision'), 'base' => 'node_revisions', 'base field' => 'vid', // This allows us to not show this relationship if the base is already // node_revisions so users won't create circular relationships. 'skip base' => array('node', 'node_revisions'), ), ); // Relationship to the 'Node' table $data['node_example']['nid'] = array( 'title' => t('Node'), 'help' => t('The particular node the color and quantity is attached to'), 'relationship' => array( 'label' => t('Node'), 'base' => 'node', 'base field' => 'nid', // This allows us to not show this relationship if the base is already // node so users won't create circular relationships. 'skip base' => array('node', 'node_revisions'), ), ); // **** End optional extra for type and relationships **** ?>

Page 76: Drupal: Views Module Guide

76

The above code adds a new 'Node example' to the view types that can be selected within the Add tab window of views. Selecting this sets the node_example table to be the base table.

If you select 'Node example' as view type, when you initially go into the edit window of views you will find the only fields available are the color and quantity fields. To get fields from other tables you need to add a relationship. Relationships may be found at the top in the same column as the fields.