Posted 06/12/2009 - 15:30 by State68
For the purposes of clarity I've used Views (with capital "V") when referring to the Drupal module, and views (with lower-case "v") when referring to the views that can be built in the Views module.
For quite a while now I've wanted to be able to access Views from my modules.
I'd worked out how to expose my modules to Views so that I could access the new tables my modules created when I built a new view, but I wanted to be able to do stuff like create a view that listed a load of users, and then have these users displayed in a drop-down list on some form that was created by my module.
Like much of Drupal, getting to the guts of Views wasn't particularly well documented. But (also like much of Drupal) once I'd got everything figured out accessing views was really straightforward and flexbile.
The first thing to realise is that each different view is an object. Each object contains all the stuff that is needed in order for your view to be displayed.
There are a couple of ways to load a view. The first way is to use views_get_view( ):
<?php
$view = views_get_view('the_name_of_your_view');
?>The second way is to use views_get_all_views( ). This works in a very similar way, but it loads all of your views into one array:
<?php
$all_views = views_get_all_views();
?>So in this example, $view is exactly the same as $all_views['the_name_of_your_view']. Both are objects; in order to see how they're made up do a print_r on them, or see this picture. The basic idea is that you can access bits of the view object just like you can access bits of the node or user object.
To get to the realy useful bits of the view - like the SQL that generates it, for example - the view needs to be executed. Use the following function to execute the view:
<?php
$view->execute();
?>You can now get access to all sorts of other cool bits of the view - again, user print_r to check this out. One particularly useful part or the object is $view->result, which is an array containing the result of your view:
Array
(
[0] => stdClass Object
(
[nid] => 1
)
[1] => stdClass Object
(
[nid] => 2
)
[2] => stdClass Object
(
[nid] => 16
)
[3] => stdClass Object
(
[nid] => 10
)
[4] => stdClass Object
(
[nid] => 11
)
[5] => stdClass Object
(
[nid] => 12
)
[6] => stdClass Object
(
[nid] => 13
)
[7] => stdClass Object
(
[nid] => 14
)
[8] => stdClass Object
(
[nid] => 15
)
[9] => stdClass Object
(
[nid] => 17
)
)Another useful part of the object is $view->build_info['query'], which gives you the SQL which generates your view. Useful, huh?
Links:
- The Views module itself;
- The Drupal API documentation for the functions provided by Views.
