Chapter Three LLC

HOWTO: Utilize Drupal 6-style "preprocess" theme architecture in Drupal 5

Josh Koenig

Once of the biggest advances “under the hood” in Drupal 6 is the addition of the preprocess architecture to the theme layer. This is part and parcel with the deeper embedding of template files, and together they render Drupal 6 the most flexible and powerful release yet in terms of theme and design.

For those of us who still do a fair amount of work with the 5.x branch, it’s easy to be envious of those lucky enough to have these new tools at their disposal. But resist that cardinal sin! This quick HOWTO explains how to quickly turn your theme into a node-preprocessing machine, which has great benefits in terms of elegant architecture, and also future-proofing your work for the eventual Drupal 6.0 migration.

Bulding off _phptemplate_vars()

Possibly the most powerful programmatic tool in the Drupal themer’s toolkit in 5.0 is the _phptemplate_vars() function. We’ve talked before about to use this to use different template files under different circumstances. Overall, this function is a great way to make all those minor changes that are needed so that a site can have truly top-notch appearance and user-interface.

However, once your theme gets to be very complex, this function can easily become an overloaded beast of logical branches. Each new node type or special case creating new complexity, and maintaining that as your site grows can quickly become untenable.

Fear not, though. You can also use this function to implement a simple preprocessing architecture that will help you customize the data in all your node types without creating a mass of template files, and set the table for 6.0. Here’s how:

<?php
function _phptemplate_variables($hook, $vars = array()) {
  switch (
$hook) {
    case
'node':
     
$node = $vars['node']; // handy shorthand
     
$preprocess = 'phptemplate_'. $node->type .'_node_vars';
      if (
function_exists($preprocess)) {
       
call_user_func($preprocess, $vars);
      }
      break;
    case
'page':
    

 
}
}

function
phptemplate_blog_node_vars(&$vars) {
 
// your custom preprocessing here
 
$node = $vars['node']; // handy shorthand
 
drupal_add_css($vars['directory']. '/custom_blog_style.css'); 
 
$vars['submitted'] = t('Blogged by !name on !date', array('!name' => l($node->name, 'user/'. $node->uid), '!date' => format_date($node->created, 'custom', 'm-d-Y')));
}
?>

Note that you don’t need to use phptemplate_ as the prefix here; indeed it may be advisable to use your theme_name.

What this function does is quickly check for the existence of a node-specific preprocessing function, and if it exists passes through the $vars array by reference.

In this case we detect that a blog node is being rendered, and take the opportunity to include a final custom stylesheet form our theme, as well as altering the standard $submitted var.

The possibilities here are endless, and in “enterprise theming” situations where you may be dealing with upwards of 25 (or even 100!) node types, having this kind of programatic structure in your theme is invaluable for keeping things clean, elegant and extensible.

Good luck, and happy drupal theming!

Chapter Three In The H.C.!

Josh Koenig

When we first started Chapter Three, I had just relocated to rustic Trinidad California in beautiful Humboldt County, experimenting with a different pace of life from breakneck bike-borne Brooklyn. Being out in the country gave me the focused time and low cost-of-living that were essential in bootstrapping our new business, but with Matt and Zack based in SF, we always knew that’s where the natural HQ would be.

While we’re all more than comfortable with the “virtual office” setting — and we still take advantage of that kind of freedom/flexibility to combine productive work and travel, as well as to meaningfully engage our network of partners and collaborators — there are few channels with more bandwidth than face-to-face, a fact that remains true even in the era of iChat, especially when it comes to understanding client needs. We made a decision early on to go for it, to have a real office, and opened our lovely lofty 3rd Street headquarters within the first six months.

I’ve spent quite a lot of quality time there since. It’s a great space that’s given birth to some great Drupal sites, as well as a San Francsico’s #1 Boutique Fixed-Gear Bike Manufacturer. Still, I always thought there was a lot of potential for a satellite spot up here in Humboldt (the “H.C.” as I like to call it).

There are a lot of other bright tech minds up here who prefer to make a living telecommuting and enjoying the North Coast quality of life rather than joining the fray down in Silicon Valley. Seemed like an opportunity to tap into a whole new pool of talent, maybe even prove a different kind of model.

The idea appealed to my sense of how the internet is shifting economic realities and allowing new opportunities for creative minds. In contrast to the typical model of money evaporating as citizens spend their wages at franchise chain-stores on externally-manufactured goods, which let store-managers and workers draw a paycheck, but move all profits outside the local area, here we’d be positioned to bring new jobs and new capital in from all over the world.

Well I’m proud to say that as of this week, that idea is now a reality.

HOWTO: Quick jQuery Usability Tip: Automatically Clear/Restore Useful Default Values

Josh Koenig

Just wanted to post this quick trick I’ve been using lately to automagically hide/show useful default text field values (e.g. “Search” in the search box) using jQuery and the ultra-handy Drupal.settings() object.

Here’s the short and sweet copy/pastable jQuery code:

$(document).ready(function(){
  Drupal.settings.inputDefaults = {}
  $("input:text").focus(function() {
    var element = $(this);
    Drupal.settings.inputDefaults[element.attr("id")] = element.val();
    element.val('');
  });
  $("input:text").blur(function() {
    var element = $(this);
    if (element.val() == '') {
      element.val(Drupal.settings.inputDefaults[element.attr("id")]);
    }
  });
});

Basically this quick snippit will add a blank array object (ahh, the joys of moving between js and PHP) to the Drupal.settings object — which is useful for all sorts of great javascript functionality, and is integral to Drupal 6.0’s extended AHAH features; if you don’t already know it, do your self a favor and study up — and automatically fill it with any textarea’s default values when a user clicks/tabs it into focus. This lets us clear the default value, but replace it quickly if the user moves on to another element.

As listed, you probably don’t want this on your site, as it will affect things like editing nodes (e.g. title inputs will go blank when you click on them… not what you necessarily want), but it’s easy to tune this to only hit elments within certain forms since every form in Drupal has a unique #id.

Thinking about this, I decided to tune it up and actually make an extended jQuery function for this so it could be more easily applied to speecific elements like so:

$(document).ready(function(){
  // handle hide/show for text field default values in only one form
  Drupal.settings.input_defaults = {};
  $("#specific-form input:text").clearDefaultText();
});

jQuery.fn.clearDefaultText = function() {
  return this.each(function(){
    var element = $(this);
    Drupal.settings.inputDefaults[element.attr("id")] = element.val();
    element.focus(function() {
      if (element.val() == Drupal.settings.input_defaults[element.attr("id")]) {
        element.val('');
      }
    });
    element.blur(function() {
      if (element.val() == '') {
        element.val(Drupal.settings.inputDefaults[element.attr("id")]);
      }
    });
  });
}

This is a pretty nice little plugin, I think, and it shows just how easy it can be to add nice/reusable UI functionality. Happy Drupaling, and go get ‘em jQuery!

(updated w/slight improvement to jQuery fn)
(updated again w/object style improvements from comments)

The Power of Organizing Without Organizations

Josh Koenig

I simply cannot recommend highly enough Clay Shirky’s new book, Here Comes Everybody: The Power of Organizing Without Organizations. He’s been the “smartest guy in the room” when it comes to the internets for a while now, resisting the lure of hype while still appreciated the revolutionary changes we’re all living through.

This particular passage struck me as an excellent summation of what Chapter Three is all about:

We are plainly witnessing a restructuring of the media businesses, but their suffering is not unique, it’s prophetic. All businesses are media businesses, because whatever else they do, all businesses rely on the managing of information for two audiences — employees and the world. The increase in the power of both individuals and groups, outside traditional organizational structures, is unprecedented. Many institutions we rely on today will not survive this change without significant alteration, and the more an institution or industry relies on information as its core product, the greater and more complete the change will be.

One of Shirky’s overarching points is that any specific technology is only a small part of the equation. What’s critical is that the technology is ubiquitous to the point of invisibility (as the web is rapidly becoming), and that new and helpful social practices emerge which make advantageous use of the new capabilities the technology offers.

Being a part of the Drupal community is fascinating in this respect because we are at once participating in an astounding phenomena (the peer-based production of an amazingly useful piece of software) and helping others use that tool, and the methods used to make the tool itself to pursue their objectives.

It’s a jungle out here, but I wouldn’t have it any other way.

Two New Screencasts in the Drupal Dojo

Josh Koenig

Yesterday I ran an impromptu lesson in the Drupal Dojo building on last week’s introduction of Druapl 6.0’s new theme layer enhancements, namely built-in template files and automatic preprocess_functions(). We covered a topic my colleague Matt blogged about a couple weeks ago: using template files to take control of forms, which is a great way to take your UI to the next level by making it much more designer-friendly.

Check the screencast here: Fine-tuning the UI: Theming Forms With Templates In Drupal 6.0. If you’re curious about that technique in version 5, Matt’s blog post is a good place to start.

Drupal Dojo

Also, by popular demand I made a short (6 minute) mini-lesson explaining the virtues of devel.module, again in the 6.0 context with the theme_developer tool featured prominently.

Drupal 6.0: More Designer-Friendly Than Ever!

Josh Koenig

With the release of Drupal 6.0, there have been major steps forward in the theme layer. Two of the most important are the standardization of template files and their associated pre-process functions, and the addition of theme.info files which allow the overriding of whole core stylesheets.

This Sunday I gave a 45 minute overview lesson on these topics for The Drupal Dojo. There will be more later, but in brief I think with this core advance, all that remains for Drupal to be a truly designer-friendly platform is better documentation of best practices.

Check out the screencast for details.

HOWO: Use Drupal For HTTP Authentication

Josh Koenig

Very often, a Drupal website is just one of many tools being deployed on a complex project. For instance, on Chapter Three’s development servers, we keep our own SVN repositories to track custom modules and theme development.

Also often, miscellanious web services like this will want to use the standard HTTP Authentication system. Most simply this is the familiar pair a .haccess and .htpasswd file protecting a directory. Easy to set up, but it requires an admin to keep yet another list of usernames and passwords somewhere on the system which over time becomes quite a pain.

Today, while noodling with some authentication scripts for the Drupal Dojo, I decided to see if Drupal’s own user table could be used as an authentication source for these tasks. Turns out it can, and it’s pretty useful too.

Drupal User Authentication
First off, this requires mod_auth_mysql to be set up in your Apache server. There are packages for most systems, as this is a common and widely used Apache module. Once this is done, use the following code in a .htaccess file or Apache <Directory> or <Location> directive:

AuthName "Use Your Drupal Login"
AuthType Basic
AuthMySQLEnable On
AuthMySQLHost <hostname>
AuthMySQLDB <database>
AuthMySQLUser <user>
AuthMySQLPassword <password>
AuthMySQLUserTable users
AuthMySQLNameField name
AuthMySQLPasswordField pass
AuthMySQLPwEncryption md5
require valid-user

Replace the hostname, database, user and pass values just as you would when configuring your drupal installation’s setting.php file. This will let Apache access the same users table from Drupal and authenticate against it!

Limiting Access By Drupal User Role
For extra credit, you can restrict valid logins to a particular user role by replacing the AuthMySQLUserTable directive above with these two lines:

AuthMySQLUserTable "users, users_roles"
AuthMySQLUserCondition "users.uid = users_roles.uid AND users_roles.rid = 3"

The above assumes that your “admin” role has role id (rid) 3. Your mileage may vary here, and savvy SQL query writers will immediately see how you can use these two directives to limit access in all sorts of ways.

For admins with a lot of experience with mod-auth-mysql, this is all pretty obvious, but I hadn’t seen documentation specific to Drupal anywhere on the web. Hopefully this will simplify your life as much as it’s already simplifying mine!

Noel Hidalgo, "Luck of Seven" World Trekker, Interviews Dries Butyaert

Josh Koenig

My NYC comrade Noel Hidalgo (a.k.a. NoNeckNoel) has been traveling the world for the past 60 days running on “The Luck of Seven.” His goal is to visit all seven continents on money raised through ChipIn, and he’s making amazing videos, blogs, and twitters along the way.

His latest video installment comes from his visit to Antwerp, where he caught up with Drupal project founder Dries Buytaert. Dries tells the history of the project, and reflects on the inspirational and empowering potential of Drupal and open source generally via Webchick’s ascent of the Drupal Learning Curve.

Watch the video here.

Yearly Kos 2007

Josh Koenig

This weekend I have the privilege of representing Chapter Three at the Yearly Kos Convention, the mothership for progressive and Democratic online activists and organizers.

For me, it’s not just a chance to hand out business cards and schmooze; it’s also a chance to reconnect with old comrades. I came up in this industry through the Howard Dean campaign, and then Music For America and the general explosion of internet politics in 2003/04. That’s how I met Zack, how we both discovered Drupal, and how I made the transition from a journeyman freelance web developer to a real expert with the ability to champion and manage large-scale project.

I’ll post more thoughts from the conference as they settle in, but at this point the biggest things I’ve noticed are:

  • It’s a younger crowd. Still probably 35+ on balance, but there are a lot more people my age here than I saw in Las Vegas last time.
  • All the campaigns and organizations are rapidly assimilating new methods: sending videographers along for YouTube compliance, looking at local bloggers as equivalent to local newspapers, etc.
  • Older-line services such as broadcast email and CRM are becoming commodities, and the major players here are beginning to back away from trying to be the end-all be-all solution, and pursuing the ASP/API model.
  • The cafeteria here is the most price-gouging I’ve ever seen. Worse than an airport. $14 for a hamburger!

It’s interesting, because there’s a lot of energy here, but it’s a decreasingly insurgent atmosphere. The newness of things is wearing off, people and processes are becoming institutionalized, and the question now is what has really changed?

The revolution has certainly not come to pass, but things aren’t the same as they used to be. I for one hope things haven’t yet come to a point of stasis.

Increasing Drupal's Enterprise Profile

Josh Koenig

(Note: this post is part two of a three-part series: part one is here)

It can be argued that Drupal’s current rate of enterprise adoption is ok. Much of the growth within the marketplace continues to be lateral, with more and more small to mid-size organizations, projects and businesses turning on to the platform’s many advantages. This is good because it creates a diverse ecosystem of customers and enthusiasts, and a rich environment to support people who want to “turn pro” and start Drupalling for a living.

However, enterprise partners offer a chance to engage large-scale applications and drive innovation that would otherwise go by the way-side. They also offers a different kind of stability for the Drupal marketplace, and can make the kind of strategic investments that can be critical in taking the platform to the next level. In this post, I will outline what I see as the two major things the community can do to increase the rate and value of enterprise partnerships.

Marketing Marketing Marketing
One of the primary handicaps of moving Drupal into enterprise environments is a critical lack of marketing. While individual consultancies inevitably engage in some amount of evangelism, their primary focus is understandably going to be their own name and brand, as well as what it takes to close an individual deal. Any promotion of Drupal in general will be a secondary effect. While the cumulative impact of all these secondary effects is growing, it’s still no substitute for a compelling and direct pitch for the platform itself.

Drupal has benefitted from some excellent technical marketing in the form of IBM whitepapers and serious developer books from major publishers, but decision makers within large institutions are usually not engineers. Their vocabularies are peppered with acronyms like ROI, TCO and SLA, and their outlook is oriented around management concerns: streamlining processes, minimizing uncertainty, and making sure that all their decisions have “buy in” from as many of their colleagues as possible.

To someone with such a mindset, their first reaction to Drupal is likely to be confusion, if even that. The cultural disconnect between enterprise management and open-source entrepreneurialism is large, and much of the time these two worlds are barely aware of one another. That said, a strong case for Drupal can and should be made which addresses the concerns of the enterprise in their native language. This case needs to be made for more than just the value of the codebase, but rather for enterprise engagement with the community itself.

While Drupal.org is not overflowing with marketing gurus, there is probably sufficient experience to create a good set of basic talking points and other marketing source materials. People may scoff that this is just fluff, and in a way that’s true, but the fluff is important. Improving Drupal’s enterprise marketing would be a worthwhile project, and probably pretty easy to get off the ground.

Scaling Up Service (in addition to pageviews)
Beyond spreading the word in enterprise terminology, another major challenge for Drupal is the development of a sizable enough pool of experts and practitioners to make large institutions comfortable with the long-run picture. More and bigger drupal-oriented firms will need to emerge. This is partly about having larger teams of engineers to take on large (think global-scale) projects, but also about having enough of an established base and track record to make people comfortable, and about being willing/able to take on liability.

While many enterprise-scale entities have large internal IT teams, they still want and need external expertise, especially around new projects or technologies like Drupal. They will often want a contract which guarantees uptime, responsiveness, etc, and they want to engage and entity that’s willing to be legally accountable for providing that kind of service not just for initial development, but for ongoing maintenance and support over the long haul.

This is currently beyond most Drupal-oriented businesses, but it is something that more of us should aspire to provide. The alternative is writing off the high-end of the market, and/or waiting for other entities which do offer scale and liability to pick up Drupal as a line of business, which would not be likely to offer too much in the way of community dividends.

As with marketing, a lot of this can be viewed as bluster and hand-waving. Many of us know that within the world enterprise IT there are numerous stories of a good salesman selling an inferior product through a firm that looked a lot bigger and more established than it actually was. These things can and do happen. Still, we must recognize that until the Drupal community and the consultancies around it project an image that enterprise customers are comfortable with, the rate of adoption will remain slow.

That said, it would be a tragedy if our own organizational methods, communications channels, and working habits were compromised in an effort to be more enterprise-friendly. Indeed, it would probably be good if we were able to infect the Enterprise with some of the dynamism, passion and liveliness of our open-source organizational methods.

Syndicate content