You are on page 1of 21

Drupal 6 Views

What is View?
View is a powerful query builder for Drupal. Its let you fetch content from the database and present it to the user. Views can be used to generate reports, create summaries, and display collections of images and other content.

Why would I use views?


You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide 'unread forum posts'. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

Installing views module


Views do not come with Drupal installation Its necessary to install and enable Views and Views UI to start using views module

Adding a view
To add a new view, you need access admin/build/views/add menu

Adding a view

Fields

Relationships

Sort criteria

Filters

Arguments

Displaying the view as a block


We set the Defaults Style to display the elements as a HTML List. Now we will add a display of type Block

Displaying the view as a block


We do this selecting Block on the select and clicking on Add display button

Displaying the view as a block


The view with block display will appear on the blocks admin interface

Displaying the view as a block

Theming a view

Functions
views_get_view: Get a view from the database or from default views.
$view = views_get_view(my_view_name); $view->set_display(block_1); $view->set_arguments(array($my_param)); $view->execute(); foreach ($view->result as $result) { //My code here }

Functions
views_embed_view: Embed a view using a PHP snippet.
$viewName = 'MYVIEWNAME'; $display_id = 'block'; $myNodes = array(1, 2, 3); print views_embed_view($viewName, $display_id, implode('+', $myNodes));

Custom views: hook_views_pre_execute


function MYMODULE_views_pre_execute(&$view){ if ($view->name == 'taxonomy_term') { $view->set_arguments(array(1)); // I want to change first arg to '1' } }

Custom views queries: hook_views_query_alter


function MYMODULENAME_views_query_alter(&$view, &$query) { switch($view->name) { case 'myViewName': $query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC"; $query->orderby[1] = "node_title ASC"; break; } } }

Thanks

You might also like