Chapter Three LLC

drupal

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)

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.

HOWTO: Fully Theme and Customize the Drupal User Registration Form

Matt Cheney

Just a little to the left please. Flip it around. Put that on top of this. Call it by a different name. It is the little changes, that seem trivial and small, that often end up being real headaches to make and support our clients in making. Do we really want to try to build capacity with clients by teaching them to adjust #weight in hook_form_alter?

The Drupal Theming System is pretty powerful and, when done right, can offer a good avenue for our clients and their staff to edit, modify, and change their own website content. Its a lot easier to modify HTML files than Drupal module files.

A good example of where this kind of process is needed is on the user registration page. There are a lot of little bits of language and ordering to change and add, but to do so in Drupal module code can get a little hairy. Observe our technique to abstract the user/register form into a flat template file (while maintaing most of the other good Drupal goodness).

Step One: Create a theme override in your module code for the user/register form that executes a _phptemplate_callback to use a separate template file.

<?php
function theme_user_register($form) {
 
$vars = array();
 
$output _phptemplate_callback('user_registration_form', $vars);
 
$output .= drupal_render($form);
  return
$output;
}
?>

Step Two: Expand the theme override function made in step one to remove the titles and descriptions Drupal provides for the form elements. We do this in the theme function (instead of in a hook_form_alter) to preserve the original field titles so they can be used as part of any error messages coming out of form validation.

<?php
 
foreach($form as $key => $value) { // loop through top level
   
if (is_array($form[$key])) {
     
$form[$key]['#title'] = '';
     
$form[$key]['#description'] = '';
      foreach(
$form[$key] as $key2 => $value2) { // loop through second level
       
if (is_array($form[$key][$key2])) {
         
$form[$key][$key2]['#title'] = '';
         
$form[$key][$key2]['#description'] = '';
        }
      }
    }
  }
?>

Step Three: Create "rendered" versions of each of the form elements and set them as variables that can be passed to the template file.

Note: This can also be done with a generic foreach loop (similar to the one in step two) that renders each form element automatically.

<?php
 
// Set up the Vars Array
 
$vars = array();

 
// Render Specific Fields You Want on Your Registration Form
  // note - the specific location of the element in the form array varies
 
$vars['name_element'] = drupal_render($form['account']['name']);
 
$vars['mail_element'] = drupal_render($form['account']['mail']);
 
// continue for each field you want...

  // Don't Forget the Submit Button 
 
$vars['submit_button'] = drupal_render($form['submit']);

?>

Step Four: Create a template file in your site's theme directory to build the user/register form with the customized variables we defined in step three.

Note: This file needs to be the same name as specified in the _phptemplate_callback (example: user_registration_form.tpl.php).

<div class="user-register-element">
  <label>Enter a screen name:</label>
  <div class="user-register-element-input">
    <?php print $name_element; ?>
  </div>
  <div class="user-register-element-description">
    Screen names can be up to 13 characters in length.
  </div>
</div>

<div class="user-register-element">
  <label>Enter an Email:</label>
  <div class="user-register-element-input">
    <?php print $mail_element; ?>
  </div>
  <div class="user-register-element-description">
    Emails must be valid.
  </div>
</div>

<?php // continue on for each rendered form element ?>

The drupal magic here is that the user registration form is now uniquely customizable by anyone who can edit the theme template. This allows for customized "prompts" for each profile field element, without changing the site-wide field name in admin/user/profile, and it allows for customization of the username and email titles and descriptions.

This technique will need to be modified to support external modules that modify the user/register form like LoginToboggan. It also needs to take into account things like "required" fieldstates.

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!

Sling that Data: Drupal from 30 miles away

Matt Cheney

Like a fresh cup of coffee with extra soy creamer, a daily morning trip to drupal.org to browse Drupal Planet or see recent activity helps to start the day off right. The current infrastructure issues not withstanding, if I have an internet connection I can get my open source blue alien fix. But what happens if I am a long way from an internet connection? Say, in the middle of a fishing village in rural Mexico or in the woods during a 24 hour bike race. In that case, you need to sling that data.

The general idea behind slinging data is that if you have a stable internet connection somewhere in the general area (within 20 or 30 miles) you can “sling” that data through a wifi bridge to your actual destination. At the ends of the bridge should be a pretty nice wifi antenna. We used 900MHz Yagi antennas which fold down nicely and are easy for transport. The antennas can be mounted on a number of things, but we choose (for ultra portability) to mount them to large wooden rods secured by christmas tree stands. The tricky party in setting this up is to make sure that both antennas point at each other. This is pretty easy if you are just shooting wifi within your immediate line of sight, but for longer connections (like between the chapter three office and the hills of berkeley across the bay) its probably best to use GPS coordinates to set up the connection.

Once you have two antennas pointing at each other, you need to attach the antennas to a couple of generic wireless routers. We used the trusted WRT54G routers with the detachable antennas and connected the routers to the antenna using some RF cabling we found online. On a software level, we immediately replaced the standard Linksys firmware with the industrial strength DD-WRT firmware created by Brainslayer. This allowed the power frequency to be boosted to 84 mW and the routers to be associated and placed into bridge mode (a built in option). Once they were powered on and associated, wow, bam, suprise, a wifi link was activated.

Of course, with that setup the wifi range is weak. Like 1 mile, maybe 2 miles. The real secret sauce is 4 W 915 L Series Antennafier. If you hook that amplifier on both ends of the connection, set its power to full, and start the bridge your wifi signal strength will dramatically increase. Over a two mile link, this setup was able to get a better connection than a normal a normal connection between the two wifi routers in the same room! Under optimal conditions (like in the desert or by from a boat on the ocean) this could send internet 30+ miles. Under non-ideal conditions, a your range will sadly be limited to 15 to 20 miles. So find some remote locations, invite some friends, and get your do fix on a boat, beach, or backyard.

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.

Drupal in Paradise

Matt Cheney

Our office in San Francisco is pretty cool, but to commemorate our first year in business we decided to roll down the coast and do a little Drupal development somewhere even more wonderful than San Francisco. So we got ourselves some airline tickets, got hooked up with a great house with glass walls right on the beach, invited a few friends, and moved the operation to a small fishing village about two hours by dirt roads north of Cabo San Lucas. Why do development with Drupal in an office when you can do it on the beach?

We are equipped with some WIFI internet broadcast from an amped twenty foot omni-directional antenna, a couple bags of vegetarian food brought from rainbow grocery in San Francisco, Zack’s overflowing iPod, and all the fresh oranges, mangoes, avacados, cantaloupes, and strawberries we can eat. It’s a perfect setup to spend the next two weeks building websites, rocking emails, doing a little skype with our clients, and having a two week long Drupal beach party. There are definitely plenty of distractions and we might have some complications from an incoming hurricane, but there is a certain tranquility in coding from a beach in Mexico.

Drupal Represents at Defcon

Matt Cheney

Las Vegas casino magnet Steve Wynn was rumored to say that Defcon was “a dangerous and chaotic mess” that will “never set foot in one of my hotels again”. I guess his comments are understandable. During one conference the attendees reprogrammed Wynn’s hotel elevators to stop on every floor and rerouted the pay per view channel to the casino’s internal CCTV. Oh well, he probably said the same thing about Britney Spears after kicking her out of his hotel.

While Josh was out wowing the liberal bloggers this year, I was in Las Vegas with a good mix of 6000 reverse engineers, computer security professionals, federal agents, academics, and freelance hackers. There were solid talks about intellectual property law, the Tor Project, cool WIFI tricks, and other cool topics. Plus, lockpicking and WIFI villages and a couple off the hook parties.

At such a cool, security focused event it was no surprise that Drupal made an apperance. Outside of the peer to peer praise received when I introduced myself as doing Drupal development, the internal conference Defcon TV system (dctv.defcon.org), set up by RantMedia, was running Drupal. If you consider Drupal’s track record for vulnerabilities against other CMS systems you can see why. Especially with the latest security release of Drupal 5.2, the robust Security Team and the policy of full disclosure, Drupal is poised to be the “most secure CMS”.

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