12+ screencasts on theming
The "Four weeks of Drupal" screencast series continues! The chapter on writing Drupal modules was completed a few days ago, and the theming chapter is now being published.
The theming chapter includes:
- An overview and summary screencast
- About themes – what do themes do? This episode also mentions some tools for point-and-click theming
- Adding your own CSS: This is how easy it is to create a sub theme
- A bonus screencast, showing a better way to make small CSS overrides
- Page layout: Working with regions
- Changing markup: Overriding template files, and making targeted specific overrides
- Adding template file variables: Working with preprocess functions
- More preprocessing: Adding conditioned CSS, and some other things
- Theme functions: When there are no template files to tweak
- Switching between theme functions and template files
- Theming Views: An example of a special case
- Render elements and arrays: New good stuff in Drupal 7
- Theming forms
- Using the #states property in render elements to hide and show form elements dynamically
As you can see, the screencasts don't cover all topics of theming, but I think they cover all the necessary basics and a bit more. Please note that I'm not an expert themer – the material in the last three screencasts could probably be presented in a smarter way. If you know how – please do!
The five first screencasts are already posted, and three new screencasts will be published each week until the chapter is finished. (Then it's time for the next chapter!) Curious? Check out the first episode, or get an overview of all the episodes in the series overview.
Photo by astakr at rgbstock.com.
themingBy the way: There are still some seats left at the Rules training I'm giving at DrupalCon Denver. Join and learn one of Drupal's most powerful frameworks!
Trimmed RSS for Planet Drupal
People like their Planet Drupal in different style. According to a rather non-scientific survey, two thirds prefer to get the Planet feed with full posts and two thirds reads the feed in some kind of reader.
I belong to the third that prefer the stream of posts to be trimmed to a maximum length -- it makes easier for me to scan for new posts when their lengths doesn't vary between one paragraph and five screen lengths. There has been some discussion about introducing customizable teaser length on Planet Drupal, but has proved difficult to actually get it going. While waiting for this, I whipped up a Yahoo! pipe that takes the RSS feed and trims the posts to a length that you can set yourself. If you're interested, feel free to use http://pipes.yahoo.com/itangalo/drupalplanettrimmed?_render=rss in the reader of your choice. Add "&length=500" to trim the post length to the number of characters you like -- default is 1000. (The trimming is "dumb", so no respect is taken to tags. Sorry.)
I hope this can be useful for someone more than me.
(Note: I know the webmasters on drupal.org is working hard and doing a great job. This forked feed is in no way an attempt to say that the webmasters aren't doing a good job, nor a way to try to draw people away from drupal.org. It is just a way to share something that I find useful with others.)
Interested in more smart Drupal feeds? Check out the "full modules" Twitter account or RSS feed and the "sandbox modules" Twitter account/RSS.
Caching failed with panels in legacy mode
Did an deploy on one of the sites that we are working with, we did not get any errors on our staging server, but when we put it out on the production server we really had a big problem with caching. Suddenly cache would choke, display white screens of sadness, just caching part of the page, etc. Crisis. At least. I tracked it down, with beads of sweat running down my face (the problem were on the production server for gods sake), and the problem were that Panels were in legacy mode and our custom layouts did not work. I found a couple of discussion on drupal.org on the subject. I updated the Skinr module to make panels running normal. Updated the database, cleared the cache a couple of times. And then, finally, everything worked ok again. I could wash my face, and make a phone call to the client to say that everything now was ok.
Lessons learned from this are several, but the most important was - never let panels work in legacy mode
PanelsCacheSkinrLegacyCaching with Varnish, Drupal 7 and Cache Actions
Using a reverse proxy cache is an efficient way to cache your web site in order to get faster response times. Drupal 7 works with reverse proxy cache servers like Varnish out of the box and the integration can be extended by using the Varnish module. I'm going to show you how the integration works in this blog post.
Set up Drupal to work with VarnishStart off with a clean Drupal installation and a working Varnish installation in front of it. You need to change some settings in Drupal to get it up and running with Varnish. Go to Administration => Configuration => Development => Performance and make the following settings:
- Check the "Cache pages for anonymous users" checkbox
- Set the "Expiration of cached pages" to a value higher that isn't none. This is important, because reverse proxy caching won't work at all otherwise.
You should now be good to go. Open up another browser (or log out), and go to your site. Open up firebug in firebox or the development tools in Chrome/Chromium and go to the network tab. Check the headers for the request to your drupal page (/). You should see something like this if everything is working:

Notice the Cache-Control Header. This header is something Drupal sends out to indicate that it wants this page cached for at least 900 seconds. If you don't see a header that looks similar to this, you have done something wrong with your caching settings.
Also look at the X-Varnish Header. If you have two Ids there, it means this page is served by Varnish. That the request took 1 millisecond is also an indicator =). You don't have to worry about the X-Drupal-Cache header. It will always be false since the Varnish will serve all cached pages.
Cache invalidationYou now have a working Varnish and Drupal setup, congratulations! The cache will be automaticly invalidated after the time you set in the caching settings has expired, and new content will be fetched. This is not good enough for some cases though, You probably want to get new content to show as soon as it is added/updated/deleted. You probably want something that resembles the standard drupal caching behavior which works like this:
- All pages are stored in the Drupal cache (cache_page table) when they are first visited. This table stores the full HTML output.
- All of the cache is flushed when content is added/updated/deleted, if you don't set the "Minimum cache lifetime" setting on the performance page. This setting will enforce the cache to live for a certain number of minutes.
This does not work with Varnish, since Drupal has no built-in way of telling Varnish when content has changed. This is where the Varnish module comes in. This module let's Drupal communicate directly with Varnish through an admin socket, which Varnish provides on a specific port, usually 6082. Follow these steps to get started with it:
- Download the varnish module as usual and enable it.
- Go to Administation => Configuration => Development => Varnish (admin/config/development/varnish) and enter the settings for that matches your Varnish setup. The module should support Varnish 2.0, 2.1 and 3.x. The Administration page has a indicator that tells you if your configuration is working.
- The default Varnish configuration usually requires that you know a secret key to access the administration socket. It's found in /etc/varnish/secret on debian, just copy it and paste it into the "Varnish secret" box.
- Make sure that you have selected the "Drupal Default" caching option.
The Varnish module comes with an alternate so called "Cache backend" for Drupal. Cache backends are swappable in Drupal, which means you can replace the standard caching functionality with another cache implementation. In order for the module to work as expected, you need to add the following to your settings.php:
$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');
$conf['cache_class_cache_page'] = 'VarnishCache';
Change the path to the Varnish module to whatever fits your installation.
We should be all good to go now, go and create some nodes on your site, and open another browser that is not logged in. Go to the new nodes and make sure they get cached by watching their headers. Then change some of your content and refresh your logged out session. Your content should have been updated, and it will be cached directly after it has been viewed the first time. You know the equivalent of the Drupal caching functionality together with Varnish.
Advanced usageThe regular caching functionality works well for smaller sites and mimic the default Drupal behavior, but if you are running a big website with a lot of visitors, you probably want to avoid the standard functionality. Having the cache for your whole website flushed at the same time can be devestating for larger websites. The easy way out is to add a Minimum cache lifetime, this will ensure that all content is not purged too often, but it will still make sure it's purge through the Varnish admin socket. The other alternative is to simply not use the Varnish module at all.
The Varnish module also comes with support for the Expire module. This module will only purge the relevant pages where your content should exist. It is still under heavy development for Drupal 7, so you should probably drop by the issue queue and help out.
Another method for purging entries in Varnish is to use The Cache Actions module. It had special support for Varnish in Drupal 6, but it doesn't need to anymore in Drupal 7, since you can use the Drupal caching system directly independently of what cache backend you are using. This is great since you can use the same technique without Varnish. The following step-by-step guide shows you how to purge the page of a particular node when it is updated, but you can do a lot more, since Rules is very powerful:
- Go to the Varnish settings page (admin/config/development/varnish) and select "None" under "Varnish Cache Clearing". This will make sure that all pages are not flushed when content is altered.
- Enable the Cache actions and the Rules UI module
- Go to Administration => Workflow => Rules and click "Create a new rule"
- Select "After updating existing content" under "Node" as the reacting event
- Add the "Clear a specific cache cid" action
- Select cache_page as your cache bin.
- Put "node/[node:nid]" in the value text area.
Try to edit one of your nodes, everything should still work. The difference now is that we are actually only purging the entry of the particular node that has been edited not the whole page. You can try this by visiting another node, notice that it is still cached by looking at the Varnish headers.
Alternative solutionsAnother interesting module to look at is the Purge module. It does the same thing as the Varnish module does, but it uses HTTP purges instead of the administration socket in Varnish.
Whatever you want from git in your make
Make-files are really powerful to use when your work in developing with Drupal with profiles. In the make-file you can download specific versions of modules, and patch them if you need, to easily set up a site. Without the need of having the modules in your own repo. And you could also download modules from git repos, on drupal.org or elsewhere, and that’s one of the big advantages. In a recent project we use a make file for our profile to download specific versions of modules, it could look like this:
projects[date][version] = 2.0-alpha4
projects[devel][version] = 1.2
projects[diff][version] = 2.0-beta2
projects[ds][version] = 1.4
They are ordinary releases that you could download from drupal.org. Sometimes we need to download modules from git instead, maybe we need to do some patching and stuff, or we need just the latest. Until now we have download a specific branch, like latest dev for the Menu Minipanels.
projects[menu_minipanels][type] = module
projects[menu_minipanels][download][type] = git
projects[menu_minipanels][download][url] = http://git.drupal.org/project/menu_minipanels.git
projects[menu_minipanels][download][branch] = 7.x-1.x
Pretty straight forward.
But then we had a problem. We needed to checkout a specific commit, and we hit the wall. How could we do that, we tried a couple of solutions. Some script magic and some ugly hacking. And suddenly I found this wonderful blog post.
And a door opened in the wall. And the sun shined on our faces.
You could check out a specific commit with
projects[menu_minipanels][download][revision] = e09d58f2c1cba50cec1aeed102614b1e5a32992d
Or you could check out a specific tag
projects[menu_minipanels][download][tag] = 7.x-1.x-dev
So you could choose fram branch, revision or tag. That is just great, if you ask me.
Just a note: you can not combine revision, tag or branch, and there a no need for that either.
gitmakedrushThe disappearing public file path setting
Some problems that you stumble upon when building Drupl sites could be unique for that project, maybe some special mix with the modules that create errors that you do not get in another mix, this could be one of unique problems. One of the Drupal 7 projects we are working on right now had some strange problems with the Public file system path. The file path did not work when we installed site (drush si profilename). If we after a site install tried to upload images to content, that did not work, and the path got screwed up (with null in it - this i believe comes from the Media module) We are using a workflow where we do site installs a lot, to handle problems early in the project.
We had to go to the settings page (that showed the right file path), change the file path, save, change the path again to what we had before. Save. And it worked. But we do not want to do that every time, do we?
So we had to solve the problem, some how. I do not where the problems come from, and did not have the time to investigate further. But we solved it with setting the variable for the path in the from the setup_config function in the .profile file of the profile we use to install the site. So you could do it like this:
function profilename_setup_config() {
variable_set('file_public_path', 'sites/default/files/');
}
I just works. Not so much a hack, just configuration. But configuration that I think we should not need to configure ourselves. Anyhow. Problem solved. In this mix.
configurationvariablessite installFree course: four weeks of Drupal
Language
English
My biggest screencast series so far is being posted, as a result of a four-week Drupal course. Feel free to join! Two days ago I had the final day of a four-week Drupal course held at Nackademin here in Stockholm. The course was a part of a two-year program called "interaction design", which means that the students are familiar with web, some PHP and not least front-end designing – but no Drupal. They worked very hard, and in four weeks we learned content management, basic site building, quite a bit of advanced site building, basics in module development and a fair bit of theming. (Needless to say, I am a very proud course teacher.)
Thanks to extra time invested by NodeOne, I was able to make record screencasts for all the topics covered by the course – which are now being posted online for anyone to use. A lot of material was already avaialble, but I still had to record some 17 hours (or 100–150 video clips) of new material. A substantial part of these videos are already available at the screencast series page, and I will continue to post 2–3 new items every week until it is all published. You will see new announcements when new parts of the series are completed.
The course material contains both tutorials and exercises as screencasts, and also a few written blog posts. Here is a quick overview:
- Chapter 1 introduces Drupal both as a web tool and a community.
- Chapter 2 contains videos about installing Drupal and managing Drupal's file base.
- Chapter 3 deals with typical editor skills – managing content, users, menus, etc.
- Chapters 4–6 concerns basic site building – content types, fields, entities and Views basics.
- Chapters 7–12 deals with advanced site building with Views, Rules and Page manager.
- Chapter 8 is dedicated to the important Features module and exporting configuration to code.
- Chapter 13 gives a step-by-step example of how module writing works, and a few coding exercises.
- Chapter 14 covers basic and a bit more advanced theming.
- Chapter 15 was added during the course, and contains some extra material mostly concerning Drupal projects as a whole.
I hope this material can be useful for you or people you know. I want more people to learn Drupal.
By the way! Don't miss the Rules Mastery training I'm giving at DrupalCon Denver, together with fago, letharion and dixon_. It will rock.
Still looking for the course? It's here! http://dev.nodeone.se/en/four-weeks-of-drupal
Drupal coursetrainingscreencastslearning DrupalStuck in the issue queue? Help out!
Language
Undefined
I recently wanted to get a full project up on drupal.org, so I created a sandbox project and made an application to get it up. Somewhere in the way I lost the Drupal spirit and started to nag about how much time the process took. It took some while, but suddenly I felt the spirit again - if I helped out in the issue queue for other applications myself, everybody will get the chance to have a quicker review, and we all together will have more modules to choose from.
There are almost always ways you could do something for the community, if you do, the community will grow and get better and better.
communityissue queueFrontend United in Amsterdam
Language
Undefined
Frontend United is going to be in Amsterdam 20-22 april this year. Is going to be sessions, talks and workshops focusing on front end development in Drupal. The venue is the Pakhuis de Zwijger. You could now signup for the newsletter on the website to get further information. Organizers are Bert Boerland, Isabell Schulz, Jesper Wøldiche, Marek Sotak and Morten Heide-Birch Jørgensen.
front endconferenceworkshopamsterdamfrontendDrupalizing a web project
I've been asked by students in the four-week Drupal course I'm doing to share some thoughts on how to interpet web projects in Drupal terms. I first thought I should make a screencast about it, but then I realized that written text is probably much better. (It came as a surprise to me, but not everything has to be screencasted.)
When using Drupal for web projects, you will save yourself a lot of work by following what's sometimes called the Drupal way. I usually describe this in the following way:
- Use community-provided resources as much as possible. Contribute as much of your work as possible back to the community.
- Rely on the big, stable and widely used module frameworks (plus core) as much as possible.
- When these framework modules aren't enough, try to patch them to make them fill your needs.
- When patching isn't enough, try to write extension and plugin modules for these frameworks.
- When extending these frameworks isn't enough, try to some the needs by writing modules of enough quality to be contributed to drupal.org.
- Only as last resort, do small hacks and custom code that are used on this site only.
What does this mean, in practice? When trying to sketch out a web project for Drupal, I usually do it this way.
Step 0: Try to understand the project
Before starting to map anything out in Drupal terms, I sit down and think about the project. More important than getting any technology working is to understand the needs of the client. Important first step is to read any description or specification that the client has provided, but you also need to talk directly to the client. Often more than once.
It is difficult to overestimate how important it is to think about the project as a whole. Sometimes this leads to the conclusion that it shouldn't be implemented in Drupal. Sometimes the conclusion is that the specification and the actual needs of the client are too far apart to start sketching any technology solutions. Often it leads to identifying a number of critical spots. Or identifying tasks that will be difficult to implement, and take as much time as the rest of the development put together.
This text, however, will not focus on these matters. It assumes that you have good understanding of what you want to build with Drupal, and want to move on to sketching out a Drupal solution for the project.
Step 1: Map out content types and entities
When actually starting to analyze the project in Drupa terms, my first step is to identify content types and other entities for the site. You will probably find a number of content types waiting in line to be written down, and you will probably have a number of more tricky cases. Should this thing be taxonomy terms, or content types? Should we have several user account profiles? Should this information be a field on another entity, or should it actually be an entity of its own?
The answers to these questions, ultimately, lie in what you will make work. On more complex projects you can expect to hit one or two dead ends, no matter on how hard you try to think ahead. Keeping these questions in mind will hopefully help you minimize the dead ends:
- How to you need to control access?
- How should the information be reused and accessed across the site?
- How should content/entities/information be related to each other?
At this point I also try to sketch out fields that should be used on entities. The by far most important field type are the reference fields (or, when applicable, relation managed by the Relation module) – other fields can be changed later on without you having to rework your map.
Step 2: User and access
My next step is often to look at the user groups for the site, and what tasks they should be able to do (or prehibited from doing). It doesn't make sense to actually create permisions at this stage, but knowing what tasks should be available to (for example) site editors will guide some decisions about what modules and technologies to use. If an editor should be able to add just about any content to just about any sidebar, you need to think about how this can be done in a safe way.
At this stage I also think about what kind of access modules are relevant for the site. Is Content Access enough? Do I need ACL as well? Is this a good case for Organic groups? (Managing customized content access is not a part of this course, though.)
Step 3: Views and accessible data
My next step is often to look at what different views are needed on the site. Many of these lists are often more or less trivial to create in Views, but there are usually a few lists dynamic that require quite a bit of thinking. What data is necessary to create this list? How can Views access that data? Is there a risk of getting duplicates in the list, or creating really heavy queries?
In almost all cases, even very tricky lists can be accomplished by using contextual filters in Views and using Page manager to pull together the data necessary to populate the contextual filter. Prototyping these lists right away can save you quite a bit of time – sometimes you assume that the data will be easily accessible through Page manager's contexts, and it turns out that you really should change the direction of a reference field, or change a text field into a term reference.
Step 4: Describing Rules tasks
Most sites have a number of custom actions and functions that editors or site visitors should be able to perform easily. Often times, this can be done using Rules and Views Bulk Operations (or just Rules if the actions should be done without any user interface). The most difficult part to analyze here is the same as with Views: Is all the necessary data available?
Some examples of custom functionality that can be managed with Rules + VBO are:
- Scheduling items to appear on the front page or at other places.
- Allowing users to subscribe to comments or content updates.
- Adding selected users to lists of different sorts.
- Automatically tag content with terms selected in a clearly specified way.
- Automatically create relations between content, in a clearly specified way.
Some functionality is too big or specialized to be managed by Rules in any sensible way – such as e-commerce sites. These cases are not discussed here.
Step 5: Taking care of the leftovers
Interpreting a web project in Drupal terms is like laying a grid over the project (or using a cookie cutter on a piece of dough) – you will have things sticking out that doesn't really fit the pattern. Not all data may be captured as entities and fields. Not all data may be fetched with Views. Not all actions may be done with Rules.
These non-conformant parts must be analyzed and taken care of. I try to do this in the following ways, most preferred on top:
- By writing extensions and plugins to the existing modules. If it makes sense, this new functionality should be provided as a patch to the main modules, or to modules extending them. If nothing else, the new functionality should be a full or sandboxed project on drupal.org – just to make the code publically accessible.
- By discussing with the client and suggesting slightly different functionality that would give (almost) the same end user service and would be much easier to implement.
- By doing custom tweaks and hacks – for example by using complex form alters or preprocess functions. As always, it is good to ask if the necessary data is avaialble, and if the code may become heavy to run.
Note that none of these steps are actually implemented at this stage (apart from discussing with the client) – this sketching is only to make it plausible that the functionality can be implemented later on.
Other analysis
There are some aspects of project analysis that are not covered in this course, but are important when doing real-world projects. The more Drupal (or web development) experience you have, the easier it becomes to spot additional aspects. Some of the more common ones are:
- Performance and scalability. While some sites have greater need for performance (page load time) and scalability (surviving many visitors), these are aspects that should be considered in all web projects. Some important questions are (1) are there any particularly heavy operations on the site, (2) how does the front page perform, (3) how many logged in users are expected and (4) what potential difficulties are there for caching?
- Localization and internationalization. Building sites in a non-English language is usually no problems, but doing fully multi-lingual sites means that you have an extra dimension to consider in just about any part of the sketch you're making for the website. Gábor Hojtsy has written an excellent series about managing multilingual Drupal 7 sites.
- Migrating data. Taking care of legacy data is a project in itself. My best advice on this is to start as early as possible, work as closely as possible with someone who knows the source data well, and never set a fixed value of how much time the migration work will take. Also, use the Migrate module.
- Integration. Most sites nowadays want to interact with data on other sites. In the simples form that means continously importing (and possibly updating) data from an external source, but it is often more useful to be able to fetch live data from other places without having to making it internal. For the former the Feeds module may be useful, and for the latter Views might be awesome.
Some example projects
In this courese you should build your own Drupal site, implementing a number of the techniques included in tutorials and exercises. I am convinced that you will learn the most if you have your own idea of what you want to build, but the list below may be useful as inspiration or fallback if you don't come up with any idea of reasonable size.
- A multi-user blog.
- A photo gallery.
- A forum or simpler community site.
- A presentation of a company where staff is divided between several departments or offices.
Using aggregation in Views
Language
English
This blogpost is a celebration of the awesome aggregation functionality in Views 3. And that I finally understood how to use them. Anyone who has been using Drupal more than just a little bit knows that Views is one of the most important tools you got in the Drupal tool box. Personally I'm convinced that Drupal wouldn't be where it is if it wasn't for Views. It just rocks.
With the 3.x branch, a number of new awesome features were added to Views – most notably the pluggable query backend, but also things like plugins for headers and footers, and/or groupings for filters and the ability to turn off node access query rewrites. But one of the additions did always escape my attempts to understand it: use aggregation. No matter how I tried to tweak the Views settings, it just didn't make sense to me.
Until a few days ago, that is. Now I know, thanks to patience from Island Usurper and emmajane. I am celebrating this by releasing three screencasts introducing aggregation, showing how to make use of aggregation and relationships, and using aggregation with other handlers or multiple-value fields.
If you don't want to watch screencasts, here's short-short version (spoiler alert!):
- Aggregation makes Views not return items from the database, but groups of items.
- You find the aggregation setting in the advanced section in Views.
- Add any fields you want to use for grouping, in aggregation mode "group similar results".
- Add any fields you want to do calculations on – sums, averages, counts, etc. (Set the appropriate aggregation mode.)
- Make sure you don't, for example, have sorting on publish date – it will make your aggregation more or less meaningless. (Views adds this by default, which was the thing stopping my attempts to understand aggregation.)
PS 1: Adding these screencasts to the old Taming the Beast screencast series, I also add a "Cred to the Views maintainers" link. If you feel that Views is a good thing, it can't hurt to let the maintainers know.
PS 2: Don't miss the Rules Mastery training at DrupalCon Denver. It will rock.
ViewsViews 3New screencast series: learn Organic Groups
Organic Groups is one of those modules that have had major changes beween Drupal 6 and Drupal 7. While the D6 version (due to legacy) had its own solutions for lists, group audience and other things, the new version utilizes entities and fields to its fullest – and relies on Views for creating lists of just about any type.
The benefits of not creating its own solutions for associating data with entities and creating lists is greatly increased flexibility. The Drupal 7 version will not – like the D6 version – have sub modules like Organic Groups Flick block, Organic group profiles or other modules that provide functionality that you normally expect to get by combining OG with your Drupal framework module of choice.
The cost of relying on other modules, though, is increased complexity. Organic Groups comes with a nice example feature that sets up the most common configuration in a snap, but to really make use of the module you need to know how to use relationships and contextual filters in Views, how to use relationships and Views content panes in Page manager, and how access and utilize data in Rules.
The screencast series Learn Organic groups tries to explain how to use OG and make the most out of it, by using it together with other important Drupal modules. I hope it will be useful.
Sass + FireSass for Firebug == Theming bliss
One of the most common complaints that I have heard against CSS preprocessors, such as Sass and Less, is that you have to change your workflow because you can’t see on which line in the CSS file a property is set on when looking in Firebug. Well, that problem has been solved!
Bilagor:NodeOne winner of three Swedish Drupal Awards
We're extremely proud to be the winners of Best Swedish Drupal site, Best Swedish Drupal technology and Swedish drupalist of the year. The Swedish Drupal Awards are awarded in the categories of best Swedish Drupal website, Swedish drupalist of the year, Swedish Drupal design of the year and Swedish Drupal technology of year.
The goal of the Swedish Drupal Awards is to recognize remarkable Drupal achievements, releases, efforts and people in Sweden in the past year.
NodeOne winner of three Swedish Drupal Awards
We’re extremely proud to be the winners of Best Swedish Drupal site, Best Swedish Drupal technology and Swedish drupalist of the year.
Rules Bonus Pack: Views
Today I wrapped up another of my crazy Rules ideas – for some time I have been thinking about letting Rules react on Views events, and also altering views as they are being built. There is now proof-of-concept functionality available in the Rules Bonus Pack project, and eventually I hope that this will be a part of Views Bulk Operations (since that module currently has the most extensive Rules/Views integration).
So, what’s new?
- There are three new Rules events available, corresponding to the pre_build, pre_render and post_render events in the Views process. Rules can hook into these and make changes to the view, or perform other actions based on the view data.
- There is a new data type available for Rules – a view display. (Actually it is a light-weight representation of a view, since view objects tend to get pretty heavy.)
- The new view data type exposes some read-only properties to Rules: machine name, human name, display (machine) name, base table, total number of rows (assuming the view has been built) and also view output (assuming the view has been rendered). These can be used in conditions and actions, just like any other data.
- There are also some writable properties that Rules can change: contextual filter values, current page number, items per page and offset.
- The view also provides its handlers, but this currently only supports reading alias names and the action ‘unset a view handler’. The latter one can, for example, be used to remove a selected field or filter when certain conditions are met.
So, what can I do with this?
This functionality is still very much being explored, so expect new things to appear (and also expect a bug or two). However, there are some cool things you should be able to do with this:
- If a view has 10–20 results, show them all on one page (instead of getting a relly short pager).
- If there are no results, redirect the user somewhere else and show a message.
- Set contextual filter values in more complex ways than Views can manage itself.
- Remove certain filters if the acting user is administrator.
- Change certain contextual value filters if the acting user is administrator.
- If you’re not on the first page of view results, remove the offset.
- Combine with Rules Bonus: Theme to set the view title to “Found 23 hits when searching for ‘pancakes’”.
- More things that you’re better at finding than I am.
The DrupalCon Denver sessions you don't want to miss
NodeOne staff have submitted some great session proposals for DrupalCon Denver. You don’t want to miss these, so be sure to rate them (highly)!
Bilagor: