Drupal 6 JavaScript and jQuery

By Matt Butcher
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Drupal and JavaScript

About this book

JavaScript: It's not just for calculators and image rollovers.

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.

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

Publication date:
March 2009
Publisher
Packt
Pages
340
ISBN
9781847196163

 

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.

 

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.

 

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.

Let's take a look at what might be called a blueprint of Drupal:

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.

Note

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.

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.

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.

Note

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.

Note

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.

Note

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.

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.

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.

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.

Note

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.

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.

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.

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.

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. 1. Devel: The main developer module.

  2. 2. Devel generate: A tool to randomly generate users, nodes, and other data for developing and debugging.

  3. 3. Devel node access: Tools for learning about what nodes are currently being accessed.

  4. 4. Macro: A tool to help you automate form submission for development and debugging purposes.

  5. 5. Performance logging: A tool to help you identify bottlenecks and memory usage.

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

Note

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.

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.

Note

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.

About the Author

  • Matt Butcher

    Matt is a web developer and author. He has previously written five other books for Packt, including two others on Drupal. He is a senior developer for the New York Times Company, where he works on ConsumerSearch.com, one of the most traffic-heavy Drupal sites in the world. He is the maintainer of multiple Drupal modules and also heads QueryPath – a jQuery-like PHP library. He blogs occasionally athttp://technosophos.com.

     

    Browse publications by this author
Book Title
Access this book and the full library for FREE
Access now