Book Image

Drupal 6 JavaScript and jQuery

By : Matt Butcher
Book Image

Drupal 6 JavaScript and jQuery

By: Matt Butcher

Overview of this book

<p>JavaScript: It's not just for calculators and image rollovers.<br /><br />Drupal 6 is loaded with new features, and not all of them are necessarily implemented in PHP. This unique book, for web designers and developers, will take you through what can be done with JavaScript (and especially with jQuery) in Drupal 6.<br /><br />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.<br /><br />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! <br /><br />If you've dipped your toe in the water of theme or module development with Drupal 6, this is the book you want to 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 through to making you a master of the jQuery library in the world of Drupal themes and modules.</p>
Table of Contents (14 chapters)
Drupal 6 JavaScript and jQuery
Credits
About the author
About the reviewers
Preface

Chapter 1. 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.

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.

Note

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.

Note

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.

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>

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.

Note

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.

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.

Note

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.

Note

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 ...>).

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.

Note

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.

    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).

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.

    Note

    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.

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.