Drupal JavaScript behaviors

stovenumerousInternet και Εφαρμογές Web

4 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

1.073 εμφανίσεις

Drupal 6 JavaScript and jQuery
Putting jQuery, AJAX, and JavaScript effects into your
Drupal 6 modules and themes
Matt Butcher
BIRMINGHAM - MUMBAI
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal 6 JavaScript and jQuery
Copyright © 2009 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of
the information presented. However, the information contained in this book is sold
without warranty, either express or implied. Neither the author, Packt Publishing,
nor its dealers or distributors will be held liable for any damages caused or alleged
to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: February 2009
Production Reference: 1180209
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847196-16-3
www.packtpub.com
Cover Image by Damian Carvill (
damianc@packtpub.com
)
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Credits
Author
Matt Butcher
Reviewers
Dave Myburgh
Paul Lovvik
Senior Acquisition Editor
Douglas Paterson
Development Editor
Swapna V. Verlekar
Technical Editor
Amey Kanse
Copy Editor
Sneha Kulkarni
Indexer
Hemangini Bari
Production Editorial
Manager
Abhijeet Deobhakta
Editorial Team Leader
Akshara Aware
Project Team Leader
Lata Basantani
Project Coordinator
Leena Purkait
Proofreader
Joel T. Johnson
Production Coordinator
Rajni R. Thorat
Cover Work
Rajni R. Thorat
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
About the author
Matt Butcher
is a Drupal programmer for
Palantir.net
. He is a member of the
Emerging Technologies Lab at Loyola University Chicago, where he is currently
finishing a Ph.D. in philosophy. He has written five books for Packt Publishing,
including Learning Drupal 6 Module Development, Mastering OpenLDAP, Managing
and Customizing OpenCms 6, and Developing Websites with OpenCms. He has also
contributed articles to various web sites and scholarly journals. He is an active
contributor in several Open Source projects.
Thanks to Gábor Hojtsy and Ariel Hitron for helping with the
sections on the JavaScript translation system. Greg Knaddison
and a few others organized DrupalCamp Colorado, which was the
test bed for many of the ideas and examples in the book. Douglas
Paterson and Leena Purkait not only managed the process of putting
this book together, but also worked with me to make this book
the pilot for the RAW program. Thanks also to the DrupalCamp
Chicago crowd, who provided feedback on the later chapters. John
Forsythe was instrumental in getting the early chapters prepared
for the RAW release. Dave Myburgh and Paul Lovvik provided
copious comments on the book. Larry Garfield, Nate Striedinger,
Ken Rickard, Greg Dunlap, John Wilkins, Sam Boyer, and the rest
of the Palantir team, have (wittingly or unwittingly) been great
sources of information and inspiration. Thanks also to Scott Dexter
and Samir Chopra, whose work has continued to fortify my belief in
FOSS ethics. Katherine, Anna, Claire, and Angie had to give up the
occasional Sunday afternoon activities so that I could write this book.
To them, I indubitably owe the greatest debt of gratitude.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
About the reviewers
Dave Myburgh
has been involved with computers even before the Web existed.
He studied to be a molecular biologist, but discovered that he liked working with
computers more than bacteria. He had his own computer business in South Africa
(where he grew up), which involved technical support and sales. He even created
a few static web sites for clients during that time.
He went back to science for a few years when he first came to Canada, and then
got sucked into the world of Drupal when a friend wanted a site for a local historical
society. Since then, he has once again started his own company that now builds
web sites exclusively in Drupal (he doesn't "do static" anymore). There is no lack
of work in the Drupal world, and he now balances his time between work and
family. He has also reviewed several Drupal books, including Drupal 5 Themes
and Drupal 6 Themes.
I would like to thank my family for being so supportive of me
and what I do. Working from home can be a mixed blessing
sometimes, but having the opportunity to watch my son grow
up makes it all worthwhile.
Paul Lovvik
is a Principal Engineer at Acquia and a contributor of Drupal. He
received his B.S. in Computer Science from California State University. He has spent
the last 15 years developing software at various technology companies, including
Parallax Graphics, Sun Microsystems, and Openwave Systems. He has experience
with developing in C, C++, Java, JavaScript, and PHP.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Table of Contents
Preface
1
Chapter 1:
Drupal and JavaScript
7
Do you speak...?
8
PHP
9
SQL 1
0
HTML 1
1
CSS 1
2
XML 1
3
JavaScript 1
4
Drupal's architecture 1
5
The Drupal Core 1
6
The Theme Engine 1
8
Modules 1
8
Users, nodes, and blocks 1
9
Users 1
9
Blocks 2
0
Nodes 2
2
Drupal JavaScript development tools 2
3
A good editor 2
4
Firebug 2
4
The Drupal Devel package 2
6
Summary 2
8
Chapter 2:
Working with JavaScript in Drupal 2
9
How Drupal handles JavaScript 3
0
Where Drupal JavaScript comes from? 3
1
Project overview: printer-friendly page content 3
2
The printer script 3
3
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Table of Contents
[
ii
]
Drupal coding standards 3
4
Stylistic differences between PHP and JavaScript 3
5
The first lines 3
6
The print() function 3
8
Creating a theme 4
3
Full themes and subthemes 4
4
Creating a theme: first steps 4
5
Creating a theme directory 4
5
Creating the .info file 4
7
Adding files to the theme 4
8
The CSS file 5
2
Adding JavaScript to a theme 5
2
Overriding a template 5
2
Adding the script file 5
7
Summary 5
8
Chapter 3:
jQuery: Do More with Drupal 5
9
jQuery: the write less, do more library 5
9
A first jQuery script 6
2
Getting jQuery 6
2
Starting with a basic HTML document 6
2
Querying with jQuery (and the Firebug console) 6
3
Bye bye, jQuery(); hello $() 6
7
Doing more with jQuery 6
8
Using jQuery in Drupal 7
1
Don't do it yourself! 7
3
Project: rotating sticky node teasers 7
3
The StickyRotate functions 7
6
The init() function 7
8
The periodicRefresh() function 8
6
Adding an event handler with jQuery 8
9
A brief look backward 9
1
Summary 9
2
Chapter 4:
Drupal Behaviors 9
3
The drupal.js library 9
3
Drupal JavaScript behaviors 9
5
Defining a behavior to handle repeatable events 9
6
Telling Drupal to attach behaviors 9
8
Context and behaviors: bug potential 9
9
Project: collapsing blocks 10
2
Utilities 10
7
Checking capabilities with Drupal.jsEnabled 10
7
The Drupal.checkPlain() function (and the jQuery alternative) 10
8
The Drupal.parseJson() function 11
1
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Table of Contents
[
iii
]
The Drupal.encodeURIComponent() function 11
2
The Drupal.getSelection() function 11
3
Project: a simple text editor 11
3
The main behavior 11
8
Step 1: find text areas that need processing 11
9
Step 2: add event handlers 11
9
Step 3: attach the button bar 12
0
Summary 12
6
Chapter 5:
Lost in Translations 12
7
Translations and drupal.js 12
8
Translation and languages 12
8
Turning on translation support 12
9
Getting and installing translations 12
9
Configuring languages 13
0
Adding the language 13
0
Configuring languages 13
1
Using the translation functions 13
3
The Drupal.t() function 13
4
The Drupal.formatPlural() function 13
6
Adding a translated string 13
8
Project: weekend countdown 13
9
Translating the project's strings 14
4
Changing a translation file 15
3
Summary 15
4
Chapter 6:
JavaScript Theming 15
5
Theming in PHP, theming in JavaScript 15
5
The Drupal.theme() function 15
9
Project: menus and blocks 16
1
Adding a block with a menu in it 16
2
Theming a block 16
4
Theming a menu 16
8
The JavaScript theming module 17
4
Theming tables 17
5
Sending notifications to the user 17
8
Adding links 17
9
Project: templates for JavaScript 18
0
The node template 18
1
From a template to a system: what next? 18
3
A template system 18
4
Theming with templates 18
7
Using the template system 19
2
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Table of Contents
[
iv
]
A word of warning 19
4
Summary 19
6
Chapter 7:
AJAX and Drupal Web Services 19
7
AJAX, JSON, XHR, AHAH, and Web 2.0 19
8
Web application and Web 2.0 19
8
The position of AJAX in Web 2.0 19
9
Getting technical 20
0
Move over, XML 20
1
Project: web clips with RSS and AJAX 20
4
Really Simple Syndication (RSS) 20
5
The project goals 20
6
Creating the web clips tool 20
7
The WebClips behavior 20
9
The WebClips.showItem() function 21
7
Project: real-time comment notifications 21
9
Displaying comments as notifications 21
9
Installing Views and Views Datasource 22
0
Creating a JSON view 22
1
The comment watcher 22
6
The comment watcher behavior 23
0
The CommentWatcher.check() function 23
1
Theming the comment notification 23
5
Managing cookies 23
7
Summary 24
0
Chapter 8:
Building a Module 24
1
How modules work 24
1
The module structure 24
2
The directory 24
3
The .info file 24
3
The .module file 24
3
Where do modules go? 24
3
Project: creating a JavaScript loader module 24
4
Creating the module directory 24
5
A JavaScript sample 24
6
The module's .info file 24
7
A custom addition 24
8
The .module file 24
8
The jsloader_help() function 24
9
The jsloader_init() function 25
2
Project: the editor revisited 25
6
First step: creating the module 25
6
The CSS file 25
8
The bettereditor.module file 25
8
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Table of Contents
[
v
]
The bettereditor.js script 26
8
The editor() behavior 27
2
The insertTag() function 27
7
The addTag() theme 27
8
The button() theme function 28
4
The buttonBar() theme function 28
5
A last question 28
5
Summary 28
6
Chapter 9:
Integrating and Extending 28
7
Project: autocompletion and search 28
7
The theory 28
8
Our plan 28
9
First step: creating the taxonomy 28
9
The new module 29
1
The search autocomplete JavaScript 29
4
Project: jQuery UI 29
9
What is jQuery UI? 29
9
Getting jQuery UI 30
0
The accordion module 30
1
The .info and .module files 30
2
The accordion JavaScript 30
3
Project: writing a jQuery plug-in 30
9
The plug-in code 31
0
A brief introduction to closures 31
2
The divWrap() function 31
5
Summary 31
8
Index 31
9
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Preface
JavaScript: It's not just for calculators and image rollovers.
Drupal 6 is loaded with new features, not all of which are necessarily implemented
in PHP. This unique book, for web designers and developers, will guide you through
what can be done with JavaScript (and especially with jQuery) in Drupal 6.
With the combination of the powerhouse jQuery library, with its own robust set of
JavaScript tools, Drupal 6 comes with a pre-packaged killer JavaScript environment.
Cross-platform by nature, it provides all of the tools necessary to create powerful
AJAX-enabled scripts, gorgeous visual effects, and view-enhancing behaviors.
In addition, Drupal developers have ported some of its most powerful PHP tools
(like a theming engine and support for localization and language translation) to
JavaScript, making it possible to write simple scripts, where once only complex PHP
code could be used.
This book gives you the keys to the toolbox, showing you how to use Drupal's
JavaScript libraries to make your modules and themes more dynamic, interactive,
and responsive, and add effects to make your Drupal site explode into life!
If you've dipped your toe in the water of theme or module development with Drupal
6, this is the book that will make the look and behavior of your work something
special. With it's project-based approach, this book is carefully constructed to guide
you from how JavaScript fits into the overall Drupal architecture, to making you
a master of the jQuery library in the world of Drupal themes and modules.
What this book covers
Chapter 1 focuses on various languages and technologies used in Drupal. We will
have a high-level overview of the Drupal architecture followed by an examination
of some key Drupal concepts such as users, blocks, and nodes. From there, we will
move on to developers tools and learn about a few utilities that can expedite Drupal
JavaScript development.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Preface
[
2
]
Chapter 2
covers the basics on how JavaScript can be used within Drupal 6. We will
begin by exploring how JavaScript is included in Drupal pages, and then create our
first script for Drupal.
Chapter 3 focuses on jQuery. Initially, we will look at jQuery independently of
Drupal, and then we will take a closer look at how jQuery is integrated with Drupal.
Chapter 4 focuses on Drupal Behaviors and the major utility functions provided by
drupal.js, which provides functions for behaviors, translation, theming, as well as
other utility functions.
Chapter 5 focuses on the translation system in Drupal, and the JavaScript tools
that are used in conjunction with that system. We will look at installing and
configuring multiple languages using JavaScript functions, and then extracting
and translating strings.
Chapter 6 focuses on the JavaScript theming system. We will look at the JavaScript
theming module, and examine some of the themes and user interface tools that it
provides. We will implement our own template system based on HTML, CSS,
and JavaScript.
Chapter 7 focuses on the AJAX family of tools. We will learn to use jQuery's
built-in AJAX support to get content from Drupal, and also use JSON (JavaScript
Object Notation) as a JavaScript-friendly way of sending data from Drupal.
Chapter 8 focuses on module development. We will discuss how modules work,
and will learn how to create modules and use them for adding JavaScript features.
We will also learn to make our JavaScript available to other modules.
Chapter 9 focuses on advanced topics. We will look at integrating existing Drupal
JavaScript tools with our own site design, and then we will see how to extend the
JavaScript libraries with the jQuery UI library. We will also extend jQuery's library
with our own functions, building a jQuery plug-in in the process.
Who this book is for
This book is for web designers and developers who want to add JavaScript elements
to Drupal themes or modules to create more flexible and responsive user interfaces.
You are expected to know about the basic operation of Drupal, and be familiar with
the concept of theming and modules in Drupal. No experience with creating themes
or modules is required.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Preface
[
3
]
You will also need to know the basics of client-side web development. This includes
HTML, CSS, but you should also have a rudimentary grasp of JavaScript syntax.
Familiarity with PHP programming will be an advantage, since we will be writing
PHPTemplate files and (at the end) creating Drupal modules. However, PHP is
covered thoroughly enough that even the PHP neophyte will not find the text
too demanding. The book also covers the jQuery JavaScript library and its use in
Drupal, but no knowledge of jQuery is expected. You will learn everything you
need in this book.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows, "We can include other contexts through the
use of the
include
directive."
A block of code will be set as follows:
Drupal.behaviors.countParagraphs = function (context) {
if ($('#lots', context).size() > 0) {
return;
}
else if ($('p', context).size() > 5) {
$('body').append('<p id="lots">Lots of Text!</p>');
}
};
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items will be made bold:
if(sel.id == txtareaID && sel.start != sel.end) {

txtareaEle.value = SimpleEditor.insertTag(
sel.start,
sel.end,
$(this).hasClass('bold') ? 'strong' : 'em',
txtareaEle.value
);
sel.start = sel.end = -1;
}
New terms and important words are introduced in a bold-type font. Words that you
see on the screen, in menus or dialog boxes for example, appear in our text like this:
"clicking the Next button moves you to the next screen".
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Preface
[
4
]
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book, what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to
feedback@packtpub.com
,
making sure to mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send
us a note in the SUGGEST A TITLE form on
www.packtpub.com
or email
suggest@packtpub.com
.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on
www.packtpub.com/authors
.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things
to help you to get the most from your purchase.
Downloading the example code for the book
Visit
http://www.packtpub.com/files/code/6163_Code.zip
to directly
download the example code.
The downloadable files contain instructions on how to use them.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Preface
[
5
]
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in text or
code—we would be grateful if you would report this to us. By doing this you can
save other readers from frustration, and help to improve subsequent versions of
this book. If you find any errata, report them by visiting
http://www.packtpub.
com/support
, selecting your book, clicking on the let us know link, and entering
the details of your errata. Once your errata are verified, your submission will be
accepted and the errata are added to the list of existing errata. The existing errata
can be viewed by selecting your title from
http://www.packtpub.com/support
.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide the location address or website name immediately so we can pursue
a remedy.
Please contact us at
copyright@packtpub.com
with a link to the suspected
pirated material.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.
Questions
You can contact us at
questions@packtpub.com
if you are having a problem with
some aspect of the book, and we will do our best to address it.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
If you're anything like me, you're reading this first paragraph with two questions
in mind: Is this book going to cover the topics I need? And, is this book any good?
(Again, if you're anything like me you're groaning already that the author has
lapsed into indulgent first-person navel-gazing.)
Regarding the second question, I'm obviously not the person whose opinion you'll
want. But here's the answer to the first question: The aim of this book is to provide
a practical, hands-on approach to using the JavaScript scripting language to extend
and customize the Drupal 6 Content Management System (CMS).
Drupal 6 offers JavaScript tools designed to enable developers to turn Drupal sites
into Web 2.0 platforms. That's why this book exists. We're going to see how to use
Drupal's JavaScript support to assemble the building blocks needed to enhance
the client-side experience. Tools such as jQuery, language translation, and AJAX
support—all included in Drupal's core—provide powerful features that we will
explore. While we won't be developing word processors or webmail applications,
we will be developing widgets and tools that can be assembled in many different
ways to enrich the user's experience. Most importantly, we'll be doing this in a
practical and hands-on way.
What do I mean by ‘practical and hands-on'? I mean that every chapter after this one
will be organized around one or more projects. While preparing my previous book,
"Learning Drupal 6 Module Development", Packt Publishing, 978-1847194442, I came to
appreciate the power of Drupal's well-integrated JavaScript libraries. In this book,
we will use those libraries in conjunction with other Drupal technologies to create
functional pieces of code that you can use. Or even better yet, use them as a starting
point to create something even more well-suited to meet your own needs. We won't
be agonizing over the details of every function, nor will we spend a lot of time
looking at the theory. Instead, the pace will be crisp as we work on code, learn
how it works, and how it can be used.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
8
]
Let's start things off with a quick, high-level overview of Drupal. We will meet all
of these components again, so a good grounding in them will be helpful. In this first
chapter, we will cover the following:
The core technologies and languages upon which Drupal is built•
The major components in Drupal and how they work together•
The tools that you, as a JavaScript developer, can use to make Drupal •
development easier
Once we've hurtled our way through this motley list of items, we'll embark in
Chapter 2 on our first project.
Unlike many technical books, we are not going to start off with a

chapter on installing Drupal. There are many resources on this
already, including the well-written Drupal installation notes
that are included with Drupal. If you need to install Drupal, go to
http://drupal.org and download the latest 6.x series Drupal
package. The archive you download will contain a file named INSTALL.
txt that contains detailed installation instructions.
Let's begin by looking at the languages in which Drupal is written.
Do you speak...?
Most of the time, people (including myself) talk about Drupal as a PHP-based CMS.
PHP (a recursive acronym for PHP: Hypertext Preprocessor) is a web-centered
programming language. Talking about Drupal as a PHP application makes sense as
most of the server-side programming logic is indeed written in PHP.
But PHP is not the only language used by Drupal. Surprisingly, there are at least
six different languages used in Drupal: PHP, SQL (Structured Query Language),
HTML (HyperText Markup Language), CSS (Cascading Style Sheets), XML
(eXtensible Markup Language), and—you guessed it—JavaScript.
You might be asking, "At least six? Can there be more?" Yes, there can be
more. Drupal can be extended to support innumerable languages. This
can be done through its module system.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
9
]
The focus of this book will be on JavaScript. We will make use of a lot of HTML,

CSS, and also a subset of PHP. But Drupal's use of these technologies is fairly
standard, and we won't be doing anything really startling with HTML or CSS.
In Drupal, XML is used primarily to provide support for RSS (Really Simple
Syndication) feeds and AJAX (Asynchronous JavaScript And XML). In fact,
we will be using Drupal's XML support for these things. We will make use of some
light PHP programming—mainly for writing templates—but it won't play a major
role in this book. We won't be using SQL at all.
While we encounter many Drupal technologies, we will stay on target. JavaScript
will be our focus.
Okay, so Drupal makes use of several languages. Impressive, sure...but why? And
how? Let's take a two-minute tour of each of these languages to learn about the roles
they play.
PHP
PHP (
http://php.net
) is a procedural, object-oriented scripting language. Originally,
it was designed to perform server-side HTML processing like the antiquated SSI
(Service Side Includes) technology introduced in the mid-1990s. But while SSI grew
stale and died off, PHP developers kept growing their language. With each release
of the PHP engine, it grew in power and flexibility. As a result, it achieved superstar
status among web developers. These days, you're likely to find PHP on Windows,
Mac, Linux, and UNIX boxes across the Web. Since PHP can now be used to write
shell scripts and even windowed applications, you might find it doing more than just
driving a web site.
Drupal's server-side logic is written primarily in PHP. How so? When the web server
hands Drupal a connection from a client, it is the PHP code that gets executed to
handle the client's request. Other than the queries passed to the database, all of the
processing that the server does is handled by PHP.
While this is a book on JavaScript, we will be writing some PHP code. Not a PHP
developer? Don't worry. For the most part, we will be using a very small subset
of PHP. We will be calling basic functions to handle formatting and layout from
Drupal's template engine called PHPTemplate. The purpose of PHPTemplate is
simple: Provide an easy method for inserting dynamic values into HTML. You only
need know a handful of PHP functions to be able to use PHPTemplate. This book
will cover those functions without assuming you're already a PHP ninja.
Here's a quick example of what PHPTemplate programming looks like:
<strong><?php print t("Good Day");?></strong>
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
10
]
The
<strong>
and
</strong>
tags are just you're regular old HTML tags. The
<?php
... ?>
part indicates that the enclosed information is PHP code that the server
should execute. Inside that is the line
print t("Good Day")
, which simply uses the
t()
function to translate
Good Day
into whatever the user's language is. Then using
the print directive, prints the results to the HTML. Assuming my preferred language
is German, the previous code would generate something like this:
<strong>Guten Tag</strong>
That's the sort of PHP we'll be writing in this book.
Drupal's translation features, which are available in JavaScript, will be
covered in Chapter 4.
Towards the very end of the book, we will use a little more PHP to build a Drupal
module. This might be a little more demanding, but those are the chapters you can
skim if you don't want to learn PHP. If you're interested in learning more about
PHP development, there are several other great books available, including
(shameless plug) my book Learning Drupal 6 Module Development Packt Publishing,
978-1847194442.
SQL
SQL is an acronym for Structured Query Language. What do you query with SQL?
A database! SQL is the industry standard for writing queries that relational database
systems can then parse and execute. But while the language is standardized, there
are multiple flavors of SQL. Each database program seems to use a slightly different
version of SQL—supporting some subset of the standardized language while also
adding on additional database-specific features.
Historically, Drupal development has targeted the open source MySQL database
(
http://mysql.com
) as the "official" database. Another popular open source
database, PostgreSQL (
http://postgresql.org
), is also supported by recent
Drupal releases (though not all add-on modules currently support it).
While you will need to run a database in order to use Drupal, we won't be making
much use of the SQL language in this book. Drupal provides built-in tools that we
can use to get the content we need out of the database without having to write our
own queries.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
11
]
HTML
HTML is the primary format for web-based content. As you undoubtedly know,
the purpose of HTML is to "mark up" a text using tags, sometimes with attributes
to provide instructions on how the document is structured and how it should look
when displayed in a browser.
Tags and elements
An HTML tag looks like this: <p>. Most tags in HTML are paired, with a
start and end tag. A tag may also have attributes, such as type="text/
javascript", and may also surround some content. When we talk
about the tag, plus the attributes and its content, we use the term element.
For example, to indicate that a piece of text is particularly important, we would put it
inside of the
<strong></strong>
tags:
The <strong>important</strong> thing.
By default, most visual browsers render the content of the
<strong>
element as
bold text as seen here:
The important thing.
HTML's evolution has been a rough one. Initially, it was designed just to provide
structural information about the contents. But somewhere along the line, it also
became a tool for encoding layout and styling information. Combining the two
seemingly similar ideas of structure and style seemed like a good idea. But in
practice, it made for some very messy code.
The family of HTML specifications can be found online

at http://www.w3.org/html/.
On another front, XML (which we will look at in a moment) evolved separately.
Then, at some point, reconciliation between the HTML standards and the XML
standards was attempted. The outcome of this endeavor was XHTML (HTML in
XML). XHTML is now considered to be the right way to write HTML. In this book, we
will strive to use well-formed XHTML. You may notice this in the following ways:
All tags and attribute names will be in lowercase.•
All tags will be closed. That means a tag will either appear in the opening •
and closing pairs (
<strong></strong>
), or as a single self-closing tag
(
<br/>
—note the forward slash (
/
) before the closing angle bracket (
>
)).
All documents will start with an XML declaration (•
<?xml

... ?>
) and a
document type declaration (
<!DOCTYPE html

...>
).
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
12
]
One of the primary roles of JavaScript (as we shall see many times) is to interact
with the document represented in HTML. Consequently, we will be using HTML
frequently in this book.
CSS
Another design principle driving XHTML is that the layout and styling information
embedded directly in the HTML should be limited to what is absolutely necessary.
Styling and layout should primarily fall in the purview of a style-specific language.
What language might that be? Cascading Style Sheets (CSS) is the
de

facto
styling
language in today's browsers.
The CSS family of standards is found here:
http://www.w3.org/
Style/CSS/.
CSS is a declarative language whose central task is to map styles to patterns of
markup in an XML or HTML document. Or, plainly speaking, CSS identifies
certain pieces of HTML and tells the browser how those pieces should look.
Earlier we looked at this piece of HTML:
The <strong>important</strong> thing.
I noted that by default, a browser would display this as highlighted text. But with
CSS, we can tell the browser to display it differently:
strong {
font-weight: normal;
font-size: 14pt;
color: green;
text-decoration: underline;
}
This little snippet of CSS tells the browser that the text inside of
<strong>...
</strong>
should look like this:
The weight of the font (how bold it is) should be normal, not bold.•
The font size should be 14 points high. Assuming that the surrounding text is •
12 points, this will appear larger than surrounding text.
The text color should be green.•
The text should be underlined.•
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
13
]
Thus, when rendered through the browser, the text would look more

like this:
Another important use of JavaScript is to interact with the styles in a document.
Thus, we will be using CSS throughout this book.
XML
HTML tags are strictly defined. But what if you want to use a tag-based structure,
yet define your own tags? That's where XML comes in. Using XML, you can keep the
markup syntax while defining your own tags and attributes.
For example, if we want to develop an XML-based document type that describes a
pen, the markup might look something like this:
<?xml version="1.0"?>
<pen type="ballpoint">
<ink>
<color>black</color>
<permanent>true<permanent>
</ink>
<shaft>
<color>clear</color>
<material>plastic</material>
</shaft>
</pen>
Basically, it looks like an HTML document, but the tag names and attributes have
been developed specifically for the purpose of describing a pen.
Creating special-purpose markup languages is certainly the most common use of
XML. But there are many technologies that complement, co-operate with, and extend
XML to provide advanced capabilities. You can peruse
http://w3.org
to get an idea
of these technologies.
Here, we won't be using anything sophisticated. Our interest will be limited to plain
old XML and a few standard XML-based formats (such as the RSS).
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
14
]
JavaScript
The star of the show has been saved for the last. JavaScript is an object-oriented
scripting language designed to run within a web browser. Let's unpack this statement:
Object-oriented• : Like other object-oriented programming languages,
JavaScript uses objects as a way of organizing code. (We will come back to
objects later.) But JavaScript doesn't provide all of the usual object-oriented
constructs you may have seen elsewhere. There are no classes in JavaScript,
nor are there private and protected object methods. But, the bottom line is
simply this: JavaScript employs the methodologies and principles espoused
in other modern object-oriented languages. We will use this to our advantage.
The use of the term "object-oriented" to describe JavaScript is contested.
Sometimes, JavaScript is called Object-Related because it does not have
all of the constructs that object-oriented languages typically contain.
Currently, calling JavaScript object-oriented seems to be in favor, since
JavaScript can be made to emulate any features that it does not have
built-in. JavaScript 2.0 will be a fully object-oriented language.
Scripting language
• : Many languages—such as Java, C++, and C#—are written
in plain text, and then compiled into a format that is not readable by humans.
The compiled code is then executed by the computer when the program is
run. Scripting languages differ from these. They are not pre-compiled. Instead,
they are delivered for execution as plain text files. Then an interpreter takes the
responsibility for executing the script. JavaScript-enabled web browsers have
JavaScript interpreters embedded inside.
Web browser-centered• : JavaScript was initially developed as a special-purpose
language designed to provide interactivity to the otherwise static HTML pages.
While talented software developers have found other uses for the JavaScript
language, it is still the scripting language of choice for cross-browser web
scripting. Our use of it will be limited to web programming with Drupal.
So why does Drupal use both PHP and JavaScript? Why not use just one? The reason
has to do with where the code is executed.
In a web application, PHP is always executed only on the server. The server runs the
PHP code and then sends the resulting information to the client. The information
that is sent is usually in the form of HTML, CSS, or JavaScript.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
15
]
The web browser will never see a line of PHP code. It will all be taken care of by

the server.
So the PHP runs on the server and then sends the results to the client. The browser
takes that information—HTML, CSS, and JavaScript—and uses it to display the page.
As we saw earlier, HTML and CSS are used to describe and format the content.
The JavaScript serves a different purpose.
When the browser encounters a JavaScript file, it fires up the JavaScript interpreter
and passes the script to the interpreter. Remember that this activity is happening on
the client machine, not the server.
The script can then interact with the other content that the server has sent to the
browser. The script can add or remove CSS styles. It can add or remove elements
from the HTML. It can rearrange a web page. It can (using AJAX) request additional
content from the server and then insert that content into the document. It can make
the user interface more attractive and easier to use. In a nutshell, it can take a static
page and add some interactivity.
Does this description make JavaScript sound like a toy language? A gimmicky way
of adding glitz, but nothing more? That might have been the case in the beginning,
but it's come a long way. Web-based applications driven by advanced JavaScript
(Web 2.0) are today's Internet darlings.
That's where we are headed. In the coming chapters, we are going to use JavaScript
to add client-side functionality to our Drupal site.
We've taken a high-level overview of the different languages that Drupal employs.
Now we're going to take a different perspective. We're going to look at the many
parts that make up Drupal and see how they all connect.
Drupal's architecture
As mentioned in the previous section, almost all of the server-side Drupal code
is written in PHP. Just like a complex physical structure—a building or an
airplane—this code is organized into units, each of which does a particular job.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
16
]
Let's take a look at what might be called a blueprint of Drupal:
Browser
Server
Theme Engine (PHPTemplate)
Drupal Core (PHP)
Additional Modules
Database
HTML CSS JS Other
Let's look at the pieces in the diagram.
This diagram is divided into two major components: the browser and the server.
The majority of Drupal's processing is done on the server.
The PAC design pattern
On the server side, Drupal follows the PAC (Presentation-Abstraction
-Control) design pattern. The Drupal Core provides the controller. It
responds to user requests and routes them to the appropriate handlers. The
theme system provides the presentation layer. The modules (including the
built-in modules like Node) access and manipulate the data which is the job
of the abstraction layer.
The Drupal Core
At the center of Drupal is the Drupal Core. This core consists of important libraries
that Drupal must have in order to run. When a browser makes a request to Drupal,
the Drupal Core is what oversees how Drupal responds to the request. The Drupal
Core gathers data from various sources (including from the database where
information is stored long-term), and then hands that data off to the Theme Engine.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
17
]
The Drupal Core also includes some important modules. These are usually called
Core modules. All of them provide features that are often used in CMS systems. But
within the list of Core modules, there are a handful of modules that are absolutely
essential for the proper functioning of a Drupal system. Though these are not as
intimately connected with controlling the application, they provide services that
Drupal needs. You might notice these modules when you look at the Modules page
(in the Drupal administration interface: Administer | Site Building | Modules):
The screenshot shows the five absolutely necessary modules:
Block, Filter, Node,
System, and User.
While these modules are displayed with all of the other modules installed on the
system, modules marked Core – required cannot be disabled.
Later in this chapter we will discuss the data types that three of these modules
provide: nodes, blocks, and users.
The major JavaScript libraries, including
drupal.js
and
jquery.js
, are also
managed as a part of the Drupal Core. These libraries are not encapsulated in
modules, nor are they stored with the PHP libraries. They are maintained as part
of the Core, and are included with Drupal.
Much of our attention in this book will be devoted to these core libraries. The
enormously powerful jQuery library is introduced in Chapter 3, and will be used
throughout the book. The
drupal.js
library is the subject of Chapter 4, 5 and 6,
and is also used elsewhere in this book.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
18
]
The Theme Engine
The job of the Theme Engine is to take the data given to it and format that data for
display. It might, for example, use templates to build HTML or CSS. In some cases,
it might be used to generate XML, or even email messages to be sent from the local
mail server.
Once data has been formatted by the Theme Engine, it is sent back to the browser,
typically in the form of HTML, CSS, or images.
JavaScript is a slightly more complex form. It is not usually passed through the
Theme Engine. Instead, it is passed to the browser unmodified. Where does
JavaScript come from? Sometimes it comes from libraries written by developers
(the core Drupal library and jQuery are both examples of this). Sometimes it
comes from a theme. At other times, the JavaScript comes from a module.
The Theme Engine is part of the theme system. The theme system
provides an API for styling and laying out data. It loads the Theme
Engine and hands that engine data for formatting. Why the distinction?
Here is the reason. While the theme system API remains the same,
you can actually substitute different Theme Engines for the default
PHPTemplate engine (We will only use PHPTemplate, though). You can
see a list of Theme Engines at the Drupal web site: http://drupal.
org/project/Theme+engines.
Modules
Modules are the last part of server-side processing that we will look at. Drupal itself
does not try to provide every possible feature that a web site might need. Instead,
it provides common and important features and then provides a mechanism for
plugging in additional functionality.
This mechanism is called the module system. Modules can provide additional
functionality to the Drupal Core, the Theme Engine, or even JavaScript. But it is the
Drupal Core that oversees how modules get loaded and executed, and what happens
to the data they return.
There is a lot more that could be said of this system, but we have the main concepts
covered. In this book, we'll be working primarily with themes, though we will make
use of some modules as well. As we take a closer look at these technologies, we'll
build on the overview given earlier.
For our current purposes, though, it's time to move on. We need to cover a few more
high-level Drupal concepts.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
19
]
Where does our JavaScript go?
As we will see in the next chapter, JavaScript can be used in both themes
and modules. For the sake of simplicity, we will make more use of
theme-based JavaScript than module-based JavaScript. By attaching
JavaScript to themes (instead of modules), we will avoid having to write
much PHP code. In the last two chapters of the book, though, we will
create a few modules.
Users, nodes, and blocks
There are three terms that are crucial to understand when doing any kind of Drupal
development: users, nodes, and blocks.
Since the user concept is the easiest to grasp, we'll start with that.
Users
One of the required core modules that Drupal provides is the User module. This
module defines Drupal's concept of a user. As expected, a Drupal user is identified
by a username and password (or in some cases by an OpenID URL). A bundle of
information, including things such as name, email address, and preferences, is also
associated with a user.
Users can be assigned roles. Roles determine what permissions a user has.
By default, there are two roles: anonymous user and authenticated user. An
anonymous user is one who has not signed in (and thus has no known username).
An authenticated user is one who is a member of the site (and has already signed in).
Using the Administer | User management | Permissions tool, you can assign
privileges to roles. For example, with this tool we could allow authenticated users
to post comments, but not allow that privilege to anonymous users.
Along with being able to define custom permissions, you can also define custom
roles. On sites that I administer, I often create an Administrator role. Users in that
role are typically granted broad access to the administration features of Drupal.
A special user
The first user created on a Drupal site is treated as a special administrative
user. This user is created during installation and will be allowed full
administrative access to the server regardless of role.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
20
]
As we work through this book, the users, roles, and permissions will play a part
in our coding. We will be developing code intended to be not only functional and
feature-rich, but also secure. Understanding how the user system works is a step in
the direction of securing our code.
Blocks
The next important concept that we will look at is the block system. The core block
features are provided by the Block module.
What is a block? In a nutshell, a block is a unit of organization that provides a way
for small pieces of content to be displayed in designated areas on a Drupal page. Not
terribly clear? Let's look at a screenshot:
In this screenshot, there are two arrows pointing to a couple of blocks displayed on
the page. On the left, there is a block showing the username and menu. This is the
Navigation block. Its purpose is to provide context-sensitive navigation for the user.
The Drupal logo shown beneath it is also a block, called Powered by Drupal.
On the right side is a block displayed from a custom module (the
demoblock

module that is included in the source code for this book). This block simply displays
some text.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
21
]
You can choose which blocks show up and where they will be displayed. This is
done using the Administer | Site building | Blocks tool. For example, using that
tool we can reorganize the screen shown earlier like this:
Notice that in the screenshot, the
This is a Block and Navigation blocks have
been swapped. This illustrates one of the main features of blocks: They can
be repositioned.
So what is happening behind the scenes to generate blocks? Essentially this: Drupal
modules have the ability to define blocks. When you configure a block to show up
in some region of the page, Drupal tells that module to go through the process of
creating the block.
When the module delivers its block content to Drupal, Drupal passes that
information on to the theme system. This system styles the block itself, and then
inserts that styled block into the main page template.
In the next chapter, we will be taking a closer look at the templates that come into
play when theming. Later in the book we will use JavaScript to make a block more
than just a static part of the page.
At this point, you should feel a little more comfortable with what a block is used for.
Blocks define pieces of information—lists of links, short forms, images, text, or any
other standard web content—that can be selectively displayed and positioned by an
administrator. But blocks are rarely used to provide the main content of a page.
Let's turn our attention from blocks to nodes.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
22
]
Nodes
Visually speaking, blocks typically show up as small bits of content. Nodes, in
contrast, can be thought of as the big pieces of content. Stories and pages—the two
types of content enabled by default in Drupal—are both types of nodes. Their role is
to hold and display large pieces of textual content.
In fact, that is the general purpose of a node: It encapsulates a piece of content
(usually a piece of text) and also provides additional information about that content.
Nodes typically have a body and a title. A node also tracks information about the
version of the node, the owner, creation date, and publishing state of a node. In short,
any information about that content is attached (in one way or another) to a node.
Most of the node information is stored in built-in Drupal tables in the
database. But custom node types can be defined either programmatically
(in code) or using modules such as the CCK (Content Construction
Kit). In such cases, information is indeed attached to a node, but the
underlying data storage mechanism is usually not limited to the built-in
Drupal node table. Data may be spread out in the database.
Let's take another look at the screenshot we saw earlier:
Right in the center of the page is the node object. In this case, it is a
Page node
created by clicking on the Create content link visible in the Navigation block
on the left side, followed by clicking on the Page link.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
23
]
On this page, we can see the node's title (
This is a node) and a pair of paragraphs
that make up its content.
There is more that can be done with a node than simply viewing it. We can get lists
of nodes (imagine a table of contents or a list of recent stories). We can display just a
selection from a node, as is often done on a Drupal front page. Also, with additional
modules, we can get even more sophisticated. For example, the ImageNode module
turns nodes into containers to which images may be attached. The Services module
makes it possible to serve node content as XML or other formats.
But for the sake of brevity, the most useful way to think of a node is simply as a piece
of content inside of the Drupal CMS.
How does Drupal go through the process of displaying a node? The process is
similar to the block display process. When a node is requested, the Node module
(and any necessary auxiliary modules) retrieves the node from the database. Then,
the theme system formats the node's content for display, and then inserts that
content into the main template. Once the node, blocks, and any additional content is
placed in the template, the resulting HTML document is returned to the browser
for display.
The behind-the-scenes logic for nodes is implemented in complex PHP code. But we
won't be interacting with nodes at that level.
For us, we are more interested in the node content as it is styled by the Theme Engine
and returned to the browser. JavaScript operates only on the already-rendered node
content, so there is no need to delve into node internals.
We've now, taken a look at three major concepts that will be used throughout this
book: users, blocks, and nodes. Next, we can turn our attention to the tools used to
develop JavaScript.
Drupal JavaScript development tools
One of the nice things about JavaScript development is that you don't really need
any other tools besides a text editor and a web browser. If you want to do your
JavaScript development that way, you can.
While you don't need any other tools, you can become a more proficient developer
by using some additional tools. In this section, I will introduce a few tools that make
Drupal JavaScript development faster and easier.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
24
]
A good editor
Any plain text editor can be used to write JavaScript. But there are many editors
that provide features specific to JavaScript development. Features such as syntax
highlighting (automatically color-coding code to make it easier to read), automatic
code completion, and a debugger can help you write code more efficiently.
That said, there are hundreds of code editors—perhaps even thousands—that
provide some degree of JavaScript support. So which editor or editors should you
use? That will depend on your own preferences. In the open source world, editors
like jEdit (cross-platform) and Notepad++ (Windows) provide basic support without
lots of frills. If you are also a PHP developer (or you write code in other languages),
IDEs such as Eclipse, Aptana, and NetBeans provide good integration. Even
Vim (Vi Improved) and Emacs provide JavaScript support. Also, there are many
commercial packages, such as TextMate for the Mac, that provide environments
for coding in JavaScript.
If you don't have an editor that you already feel comfortable with, I suggest
trying a couple of different ones. Start with an easy-to-use editor like jEdit
(
http://jedit.org
) or Notepad++ (
http://notepad-plus.sourceforge.net/
).
Firebug
Unlike editors, when it comes to debugging JavaScript, there is a clear candidate.
The Firefox extension Firebug tool (
https://addons.mozilla.org/en-US/
firefox/addon/1843
) is not only a good way of debugging your JavaScript code,
but also a tool for analyzing HTML, the DOM, CSS, and network performance. With
the built-in JavaScript command line, you can interactively execute JavaScript from
within your browser.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
25
]
For example, here's a screenshot of Firebug inspecting the HTML contents of the
page we've been looking at:
Firebug is running inside of Firefox (though I have hidden the Firefox toolbars to
squeeze more into the screenshot). In the lower-left pane, Firebug is displaying an
HTML representation of the current state of the document.
To the right of the HTML browser is the CSS browser, which is currently displaying
the styles attached to the highlighted HTML element. Since the
<body>
tag is
highlighted in the HTML, the CSS viewer is showing all styles related to the
<body>
element.
Using Firebug will help you find bugs, understand what is happening in the
browser, and test out ideas right there. We will be using it in Chapter 3 to learn
the basics of jQuery.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
26
]
The Drupal Devel package
Seasoned Drupal developers have created special Drupal modules designed to make
developing for Drupal easier. The Devel package contains some of the most useful
developer modules.
Devel provides a suite of utilities to help developers work on Drupal. The Devel
package can be downloaded from the Drupal website:
http://drupal.org/
project/devel
. This package provides five modules:
1.
Devel
: The main developer module.
2.
Devel
generate: A tool to randomly generate users, nodes, and other data for
developing and debugging.
3.
Devel
node access: Tools for learning about what nodes are currently
being accessed.
4.
Macro
: A tool to help you automate form submission for development and
debugging purposes.
5.
Performance logging: A tool to help you identify bottlenecks and
memory usage.
6.
Theme
developer: A tool to help theme developers determine what code is
generating what part of the HTML output.
The Devel and Theme developer modules are particularly helpful for JavaScript
development. Devel gives us a handful of tools to do things such as clear server-side
caches, find out about the PHP engine, examine the server's session record, and even
re-install modules. It also provides some information about how the current theme
is structured. All of this can be useful while developing JavaScript and debugging
client-server exchanges.
Devel must first be installed using Administer | Site building | Modules, and then
the Development block must be added to one of the block regions using Administer
| Site building | Modules.
While developing themes and modules, it is often necessary to
clear server-side caches. This module is worth installing just for the
convenience of the cache-clearing feature.
The
Theme developer module (also called Themer) provides an interface for finding
out what template or Theme Engine call generates a particular piece of HTML. As
with Devel, the Theme developer module must be installed in Administer | Site
building | Modules. Once that is done, the Theme developer tool will show up in
the lower left corner of all of your Drupal pages.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 1
[
27
]
The tool looks like this:
If you check the box, then the main
Theme developer tool will open. With this tool,
you can click on any part of the page and the tool will display information about the
Theme Engine's rendering of that piece of HTML as seen here:
There are a few things to notice in the screenshot. First, around the Navigation block
in the left-hand column, there is a gray box. The box appeared when I clicked on that
block. It indicates that the HTML fragment is the one currently being examined.
Second, there is a gray semi-opaque pop-up window in the center of the image.
That is the Themer tool. It displays information about the currently selected HTML
fragment. In this case, it tells us what template file was used to generate the block
and what theme that template came from. By clicking on the lighter gray box at the
bottom of the Themer tool, we could also examine all of the variables passed to
that theme.
Finally, if you examine the screenshot you might notice that there are also bordered
boxes around the main node. Whenever the mouse hovers over a themeable element,
a red box is drawn around that element.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Drupal and JavaScript
[
28
]
In the screenshot, you might also notice the new block in the righthand
navigation. This is the Developer block we discussed. To add this block
to your own site, go to Administer | Site building | Blocks and add the
Development module to the right sidebar..
Understanding the details of how this works is not important at present. Later, when
we look at themes in more detail, you may want to use this tool to help locate which
templates are responsible for generating various parts of the page. These are the
main tools that you will be using when developing JavaScript for Drupal.
Summary
At this point we finished with our introduction to Drupal. We looked at various
languages and technologies used in Drupal. We then had a high-level overview of
the Drupal architecture followed by an examination of some key Drupal concepts,
such as users, blocks, and nodes. From there we moved on to developers tools,
learning about a few utilities that can expedite Drupal JavaScript development.
This chapter has been introductory in nature, and has been light on code. In the next
chapter we'll make a practical turn, focusing on writing Drupal-centric JavaScript
code. There, we will build our first JavaScript project.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Working with JavaScript

in Drupal
The first chapter in this book introduced Drupal and JavaScript. It also explained the
role that JavaScript plays in the Drupal 6 environment. We will now move beyond
mere explanation and take a look at the practical details and examples.
In this chapter, we will be working with JavaScript inside of a Drupal environment.
We will begin by exploring how JavaScript is included in Drupal pages, and then
create our first script for Drupal. While we're not going to cover the basics of the
JavaScript language (there are already lots of available resources on the topic), the
code we create here will be simple and straightforward.
The purpose of this chapter is to cover the basics on how JavaScript can be used
within Drupal 6. In that regard, this chapter will serve as a foundation for our
future JavaScript development. Here are the topics that we're going to cover:
Serving JavaScript from Drupal•
Creating a first script•
Creating a simple theme•
Adding JavaScript to a theme•
Without further ado, let's get going.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Working with JavaScript in Drupal
[
30
]
How Drupal handles JavaScript
How is JavaScript typically used? Mostly, it is used to provide additional functionality
to a web page, which is usually delivered to a web browser as an HTML document.
The browser receives the HTML from the server and then begins the process of
displaying the page. During this parsing and rendering process, the browser may
request additional resources from the server such as images, CSS, or Flash. It then
incorporates these elements into the document displayed to the user.
In this process, there are two ways that JavaScript code can be sent from the server to
the browser. First, the code can be placed directly inside the HTML. This is done by
inserting code inside the
<script>
and
</script>
tags:
<script type="text/javascript">
alert('hello world');
</script>
This is called including the script inline.
Second, the code can be loaded separately from the rest of the HTML. Again, this is
usually done using the
<script>
and
</script>
tags. However, instead of putting
the code between the tags, we use the
src
attribute to instruct the browser to retrieve
an additional document from the server.
<script type="text/javascript" src="some/script.js"></script>
In this example,
src="some/script.js"
points the browser to an additional script
file stored on the same server as the HTML document in which this script tag is
embedded. So, if the HTML is located at
http://example.com/index.html
, the
browser will request the script file using the URL
http://example.com/some/
script.js
.
The </script> tag is required
When XML was first standardized, it introduced a shorthand notation
for writing tags that have no content. Instead of writing <p></p>, one
could simply write <p/>. While this notation is supported by all modern
mainstream browsers, it cannot be used for <script></script>
tags. Some browsers do not recognize <script/> and expect that any
<script> tag will be accompanied by a closing </script> tag even if
there is no content between the tags.
If we were developing static HTML files, we would simply write HTML pages
that include
<script></script>
tags anytime we needed to add some JavaScript
to the page. But we're using Drupal, not static HTML, and the process for adding
JavaScript in this environment is done differently.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 2
[
31
]
Where Drupal JavaScript comes from?
As with most web content management systems, Drupal generates HTML
dynamically. In the previous chapter, we talked about how this is done through
interactions between the Drupal core, modules, and the theme system. A single
request might involve several different modules. Each module is responsible
for providing information for a specific portion of the resulting page. The theme
system is used to transform that information from PHP data structures into HTML
fragments, and then compose a full HTML document.
But this raises some interesting questions: What part of Drupal should be responsible
for deciding what JavaScript is needed for a page? And where will this JavaScript
come from?
In some cases, it makes sense for the Drupal core to handle JavaScript. It could
automatically include JavaScript in cases where scripts are clearly needed.
JavaScript can also be used to modify the look and feel of a site. In that case, the
script is really functioning as a component of a theme. It would be best to include
the script as a part of a theme.
JavaScript can also provide functional improvements, especially when used with
AJAX and related technologies. These features can be used to make more powerful
modules. In that case, it makes sense to include the script as a part of a module.
So which one is the best: modules, themes, or core? Rather than deciding on your
behalf, Drupal developers have made it possible to incorporate JavaScript into
all three:
The Drupal core handles including the core JavaScript support as needed. •
The Drupal and jQuery libraries are included automatically when necessary.
When theme developers needs to add some JavaScript, they can do so within •
the theme. There is no need to tamper with the core, or to accompany a
theme with a module.
Finally, module developers can add JavaScript directly to a module. In •
this way, modules can provide advanced JavaScript functionality without
requiring modification of the theme.
In this book we will add scripts to themes and modules. As we get started with this
chapter, we will begin with a theme.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Working with JavaScript in Drupal
[
32
]
Module or theme?
How do you decide whether your script ought to go in a theme or in
a module? Here's a basic guideline. If the script provides functionality
specific to the layout details of a theme, it should be included in a theme.
If the script provides general behavior that should work regardless of the
theme, then it should be included in a module.
Sometimes it is hard to determine when a script belongs to a theme and when it
should to be placed in a module. In fact, the script we create here will be one such
a case. We are going to create a script that provides a printer-friendly version of a
page's main content. Once we have the script, we will attach it to a theme. Of course,
if we want to provide this functionality across themes, we might instead create a
module to house the script.
Since modules require some additional PHP development, we will delay examining
them until Chapter 8. We will start out simply with a JavaScript-enabled theme.
Project overview: printer-friendly
page content
As we continue through this book, each chapter will have at least one project. In this
chapter, we are going to write one piece of JavaScript and then create a theme to
utilize the JavaScript.
The JavaScript that we will write creates a pop-up printer-friendly window, and
automatically launches the print dialog. This is usually launched from File | Print in
your browser's menu.
Once we write the script, we will incorporate it into a theme, and add a special
printing feature to the page(s) displayed with that theme. As we walk through
this process, we will also create our first theme. (Technically, it will be a subtheme
derived from the Bluemarine theme.)
By the end of this project, you should know how to create Drupal-friendly JavaScript
files. You will also know how to create themes and add scripts to them. These are
foundational tasks upon which we will build in subsequent chapters.
The first step in the process is to write the JavaScript.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 2
[
33
]
The printer script
Our script will fetch the main content of a page and then open a new window,
populating that window's document with the main content of the page. From
there, it will open the browser's print dialog, prompting the user to print
the document.
Since this is our first script, we will keep it simple. The code will be very basic,
employing the sort of classical procedural JavaScript that web developers have
been using since the mid-1990's. But don't expect this to be the norm. In the next
chapter we will dive into what John Resig, creator of jQuery, calls the "New
Wave JavaScript."
To minimize clutter and maximize the reusability of our code, we will store this new
script in its own script file. The file will be named
printer_tool.js
:
// $Id$
/**
* Add printer-friendly tool to page.
*/
var PrinterTool = {};
PrinterTool.windowSettings = 'toolbar=no,location=no,' +
'status=no,menu=no,scrollbars=yes,width=650,height=400';
/**
* Open a printer-friendly page and prompt for printing.
* @param tagID
* The ID of the tag that contains the material that should
* be printed.
*/
PrinterTool.print = function (tagID) {
var target = document.getElementById(tagID);
var title = document.title;
if(!target || target.childNodes.length === 0) {
alert("Nothing to Print");
return;
}
var content = target.innerHTML;
var text = '<html><head><title>' +
title +
'</title><body>' +
content +
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Working with JavaScript in Drupal
[
34
]
'</body></html>';
printerWindow = window.open('', '', PrinterTool.windowSettings);
printerWindow.document.open();
printerWindow.document.write(text);
printerWindow.document.close();
printerWindow.print();
};
Since this is our first piece of Drupal code, we are going to dwell on the details a little
more than we will in future sections.
First, let's talk about some of the structural aspects of the code.
Drupal coding standards
In general, well-formatted code is considered a mark of professionalism. In an open
source project such as Drupal, where many people are likely to view and contribute
to the code, enforced coding standards can make reading and understanding what
the code does easier.
When contributing code to the Drupal project, developers adhere to a Drupal coding
standard (
http://drupal.org/coding-standards
). Add-on modules and themes
are expected to abide by these rules.
It is advised that you follow the Drupal standards even in code that you do
no anticipate submitting to the Drupal project. Along with keeping your code
stylistically similar to Drupal's, it will also help you develop good coding habits for
those occasions when you do contribute something to the community.
For the most part, the official Drupal coding standards are focused on the PHP code.
But many of these rules are readily applicable to JavaScript as well. Here are a few
important standards:
Every file should have a comment near the top that has the contents •
$Id$
. This
is a placeholder for the version control system to insert version information.
Drupal uses
CVS (Concurrent Versioning System) for source code
versioning. Each time a file is checked into CVS, it will replace $Id$ with
information about the current version of the software. To learn more
about CVS, visit http://www.nongnu.org/cvs/.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 2
[
35
]

Indenting should be done with two spaces (and no tabs). This keeps the code
compact, but still clear.
Comments should be used wherever necessary.•
Doxygen-style documentation blocks (

°
/** ... */
) should be
used to comment files and functions.
Any complex or potentially confusing code should be

°
commented with
//
or
/* ... */
.
Comments should be written in sentences with punctuation.

°
Control structure keywords (•
if
,
else
,
for
,
switch
, and so on) should appear
at the beginning of a line, and be followed by a single space (
if ()
, not
if()
). Here's an example:
if (a) {
// Put code here.
}
else if (b) {
// Put code here.
}
else {
// Put code here.
}
Operators (•
+
,
=
,
*
,
&&
,
||
, and so on) should have a single space on each side,
for example:
1 + 2
. The exception to this rule is the member operator (
.
),
which is used to access a property of an object. There should be no spaces
surrounding these. Example:
window.document
(never
window . document
).
Stylistic differences between PHP and JavaScript
Not all PHP coding standards apply to JavaScript. PHP variables and function names
are declared in all lower case with underscores (
_
) to separate words. JavaScript
typically follows different conventions.
JavaScript variables and functions are named using
camel

case
(sometimes called
StudlyCaps)
. For a variable or function, the first word is all lower case. Any
subsequent words in the variable or function name are capitalized. Underscores
are not used to separate words. Here are some examples:
var myNewVariable = "Hello World";
function helloWorld() {
alert(myNewVariable);
}
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Working with JavaScript in Drupal
[
36
]
While this convention is employed throughout the Drupal JavaScript code, there
is currently no hard-and-fast set of JavaScript-specific coding conventions. The
working draft, which covers most of the important recommendations, can be found
at
http://drupal.org/node/260140
.
Here is a summary of the more important (and widely followed) conventions:
Variables should always be declared with the •
var
keyword. This can go a
long way towards making the scope of variables explicit. As we will see later
in the book, JavaScript has a particularly broad notion of scope. Functions
inherit the scope of their parent context, which means a parent's variables are
available to the children. Using
var
makes it easier to visually identify the
scoping of a variable. It also helps to avoid ambiguous cases which may lead
to hard-to-diagnose bugs or issues.
Statements should always end with a semicolon (•
;
). This includes statements
that assign functions, for example,
myFunction = function() {};
. Our
print
function, defined earlier, exhibits this behavior.
Why do we require trailing semicolons?
In JavaScript, placing semicolons at the end of statements is considered
optional. Without semicolons, the script interpreter is responsible for
determining where the statement ends. It usually uses line endings to
help determine this. However, explicitly using semicolons can be helpful.
For example, JavaScript can be compressed by removing whitespace and
line endings. For this to work, every line must end with a semicolon.
When an anonymous function is declared, there should be a space between

the function and the parentheses, for example,
function () {}
, not
function() {}
. This preserves the whitespace that would be there in a
non-anonymous function declaration (
function myFunction() {}
).
There are other conventions, many of which you will see in this book. But the ones
mentioned here cover the most frequently needed.
With coding standards behind us, let's take a look at the beginning of the
printer_tool.js
file.
The first lines
Let's take another look at the first ten lines of our new JavaScript:
// $Id$
/**
* Add printer-friendly tool to page.
*/
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 2
[
37
]
var PrinterTool = {};
PrinterTool.windowSettings = 'toolbar=no,location=no,' +
'status=no,menu=no,scrollbars=yes,width=650,height=400';
The first line is a comment with the
$Id$
tag required by the coding standards. If this
file were checked into CVS, the line would be replaced with something like this:
// $Id: print_tools.js,v 1.0 2008/07/11 08:39 mbutcher Exp $
As you can see, CVS will add some information about the version of the file. This
information includes the name of the file, its version number, when it was checked
in, and who checked it in.
Directly beneath the ID comment is the file-wide documentation block.
Documentation blocks use a special comment style beginning with a slash and
two asterisks:
/**
. Automated documentation tools can later scan the file and pick
out the documentation blocks, automatically generating API documentation for
your script.
The role of the file-wide documentation block is to explain what the code in the file
does. The first line should be a single-sentence description of the file. Additional
paragraphs may be added.
In the following line, we define our
PrinterTool
object:
var PrinterTool = {};
This code is declaring the PrinterTool variable and assigning it an empty object literal
({}). This line plays an interesting role in the structure of our application, and we will
see constructs like this both within Drupal and in the later chapters of this book.
An object literal is a notation for defining an object by using its
symbolic delimiters, rather than by using a new constructor. That is,
instead of calling the new Object() constructor, we use the symbolic
representation of an empty object, {}, to declare an empty un-prototyped
object. We will use this method frequently in this book.
The role of the
PrinterTool
object is to serve as a namespace for our application.
A namespace is an organizational tool that allows the software developer to collect
various resources together . This is done without having to worry that these
resources will be in conflict with those created by other developers.
Objects that function as namespaces should always begin with an initial
capital letter, such as Drupal or PrinterTools.
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Working with JavaScript in Drupal
[
38
]
Let's consider an example. The main function in our
printer_tool.js
file is named
print()
. But
print
is a very common name, and the built-in JavaScript
window

object already has a function named
print()
. So how do we distinguish
our
print()
from
window's

print()
?
One popular method of solving this problem is to assign objects to namespaces.
Then the developer can explicitly specify which
print()
ought to be used.
Let's look at the next line of the script for an example:
PrinterTool.windowSettings = 'toolbar=no,location=no,' +
'status=no,menu=no,scrollbars=yes,width=650,height=400';
Here we create the
windowSettings
string object, assigning it a long value that will
later be used when calling JavaScript's built-in
window.open()
function.
But
windowSettings
is defined as a member of the
PrinterTool
namespace.
If we were to insert the following code directly beneath the previous line, what
would happen?
alert(windowSettings);
We would get an error since there is no object in the current context named
windowSettings
. To retrieve the value of the
windowSettings
object, we would
need to write this instead:
alert(PrinterTool.windowSettings);
Now the alert dialog would be created and populated with the string
'toolbar=no,
location=no,status=no...'
.
That is how namespaces function. If we were to call
print()
, it would use the
window.print()
function. Remember,
window
is the default scope for browser-based
JavaScript. To call the
print()
function, which this script defines, we would have to
provide the full namespace
PrinterTool.print()
.
Since we are talking about it already, let's take a closer look at the
PrinterTool.
print()
function.
The print() function
The
PrinterTool.print()
function looks like this:
/**
* Open a printer-friendly page and prompt for printing.
* @param tagID
This material is copyright and is licensed for the sole use by Richard Ostheimer on 18th June 2009
2205 hilda ave., , missoula, , 59801
Chapter 2
[
39
]
* The ID of the tag that contains the material that should
* be printed.
*/
PrinterTool.print = function (tagID) {
var target = document.getElementById(tagID);
var title = document.title;
if (!target || target.childNodes.length === 0) {
alert("Nothing to Print");
return;
}
var content = target.innerHTML;
var text = '<html><head><title>' +
title +
'</title><body>' +
content +
'</body></html>';