Learning Drupal 6 Module Development


Learning Drupal 6 Module Development
eBook: $23.99
Formats: PDF, PacktLib, ePub and Mobi formats
$15.59
save 35%!
Print + free eBook + free PacktLib access to the book: $63.98    Print cover: $39.99
$39.99
save 37%!
Free Shipping!
UK, US, Europe and selected countries in Asia.
Also available on:
Overview
Table of Contents
Author
Reviews
Support
Sample Chapters
  • Specifically written for Drupal 6 development
  • Program your own Drupal modules
  • No experience of Drupal development required
  • Know Drupal 5? Learn what's new in Drupal 6
  • Integrate AJAX functionality with the jQuery library
  • Packt donates a percentage of every book sold to the Drupal foundation

Book Details

Language : English
Paperback : 328 pages [ 235mm x 191mm ]
Release Date : May 2008
ISBN : 1847194443
ISBN 13 : 9781847194442
Author(s) : Matt Butcher
Topics and Technologies : All Books, CMS and eCommerce, Drupal


Table of Contents

Preface
Chapter 1: Introduction to Drupal Modules
Chapter 2: Creating Our First Module
Chapter 3: The Theme System
Chapter 4: Theming Modules
Chapter 5: Using JavaScript and AJAX/JSON in Modules
Chapter 6: An Administration Module
Chapter 7: Building a Content Type
Chapter 8: Filters, Actions, and Hooks
Chapter 9: An Installation Profile
Index
  • Chapter 1: Introduction to Drupal Modules
    • Drupal's Architecture
      • Module Architecture
        • Core Modules
        • Hooks
      • Themes
    • Crucial Drupal Concepts
      • Nodes
        • Comments Are Not Nodes
      • Users
        • Access and Security
      • Blocks and Page Rendering
      • Menus
      • Forms
      • Database and Schema APIs
    • Developers' Tools
      • Developer Module
      • Coder Module
    • A Word on Our Demonstration Site
    • Summary
  • Chapter 2: Creating Our First Module
    • Starting Out
      • A Place for the Module
      • Creating a .info File
    • A Basic .module File
      • Our Goal: A Block Hook
      • Starting the .module
      • The hook_block() Implementation
        • The t() Function
        • A view Operation
    • Installing a Module
      • Step 1: Copying the Module
      • Step 2: Enabling the Module
      • Step 3: Displaying the Module's Content
    • Using Goodreads Data
      • Modifying the Block Hook
      • Retrieving XML Content over HTTP
        • The watchdog() Function
      • Processing the HTTP Results
      • Formatting the Block's Contents
    • Finishing Touches: hook_help()
    • Summary
  • Chapter 3: The Theme System
    • The Theme System's Architecture
      • Theme Templates
      • Theme Engines
      • Theme Hooks
    • Creating a Custom Theme
      • Organization of Themes
        • Sub-themes (Derivative Themes)
        • How Each Theme Functions
      • Creating a Theme
        • Creating the Theme Directory
        • A .info File
        • A CSS Stylesheet
      • A PHPTemplate Theme
        • Template Structure
        • A Page Template for Descartes
        • Using PHP to Override Theme Behavior
        • template.php Gotchas
        • Creating a Screenshot
      • From Here to a Full Theme
    • Summary
  • Chapter 4: Theming Modules
    • Our Target Module: What We Want
    • Creating a Custom Content Type
      • Using the Administration Interface to Create a Content Type
        • Content and Nodes
    • The Foundations of the Module
    • A Simple Database Lookup
      • Getting the Node ID
      • Getting the Node's Content
    • Theming Inside a Module
      • Registering a Theme
      • Creating a Theme Hook Function
      • Adding a Stylesheet
    • Overriding the Default Theme from a Theme
      • A Quick Clarification
      • Overriding the Default Theme's CSS
      • Overriding Layout with Templates
    • Summary
  • Chapter 5: Using JavaScript and AJAX/JSON in Modules
    • Picking up Where We Left Off
    • Introducing jQuery
      • Modifying HTML with jQuery
      • Checking for JavaScript Support with Drupal
        • Namespaces in JavaScript
        • Drupal's Namespace
        • A Drupal Function: Drupal.jsEnabled()
      • Delaying JavaScript Execution with jQuery
      • Including JavaScript from the Module's Theme
    • Writing a Drupal AJAX/JSON Service
      • The JSON Format
      • Our Module Roadmap
      • Server Side: Defining a New Page
        • Creating a JSON Message
        • Mapping a Function to a URL
        • Passing PHP Settings to JavaScript
      • Client Side: AJAX Handlers
        • A JavaScript Function to Get JSON Content
        • Adding an Event Handler
    • Summary
  • Chapter 6: An Administration Module
    • The emailusers Module
    • The Beginning of the Module
      • Mail Configuration
    • Registering an Administration Page
      • A Detailed Look at the Path
        • Marking the Path as an Administration Page
      • Path Registration Parameters
      • Defining the Callback Function
    • Handling Forms with the Forms API (FAPI)
      • Loading a Form with drupal_get_form()
      • A Form Constructor
      • Handling Form Results
      • The Form Submissions Callback
    • Sending Mail with the Mail API
      • Formatting Mail with hook_mail()
      • Altering Messages with hook_mail_alter()
        • Altering Hooks
        • Adding a Mail Footer
    • Incorporating the Module into Administration
      • Modifying the User Profile with hook_user()
        • Constructing the Content
    • Summary
  • Chapter 7: Building a Content Type
    • The biography Module
    • The Content Creation Kit
    • The Starting Point
    • The Module Installation Script
      • The Schema API: Defining Database Structures
        • A First Look at the Table Definition
        • Defining Fields (Columns)
        • Defining Keys and Indexes
    • Correlating the New Table with Nodes
    • The Content Creation Form
      • Overriding hook_form() Defaults
      • Adding New hook_form() Form Elements
  • Access Controls
  • Database Hooks
    • Database Inserts with hook_insert()
    • Updating and Deleting Database Records
  • Hooks for Getting Data
    • Loading a Node with hook_load()
    • Preparing the Node for Display with hook_view()
  • Theming Biography Content
    • Registering a Theme
    • The biography_info.tpl.php Template
    • The Results
  • Summary
  • Chapter 8: Filters, Actions, and Hooks
    • The sitenews Module
    • Getting Started
      • Citing Dependencies in the .info File
      • The Beginning of the .module File
    • A Simple Content Type, Defined in Code
    • Creating Filters and an Input Format
      • The Second Filter: Remove All Tags
    • Adding an Input Format
  • The Beginning of an Action
    • Implementing hook_action_info()
    • The Action Callback
  • Defining a Hook
    • Invoking a Custom Hook
      • So What Is a Hook?
    • Creating a hook_sitenews() Function
    • Implementing hook_sitenews() in Other Modules
      • In the philquotes Module
      • In the biography Module
  • Completing the Action: Theming and Mailing
    • Theme Functions
    • The hook_mail() Implementation
  • Adding a Trigger
  • Summary
  • Chapter 9: An Installation Profile
    • Introducing Installation Profiles
      • Why Use Installation Profiles?
    • Setting up a Distribution
      • Creating a Profile Directory
    • Programming Profiles
    • The .profile Script
      • The Details Function
      • The Modules List
    • The Installation Task System
      • The Profile Task
        • A Basic Profile Task
        • A Complex Profile Task
        • Moving to the Next Task
      • Registering a New Task
      • The Theme Selection Form
      • Returning to the philosopherbios_pick_theme Task
        • The Submission Handler
      • Finishing the Installation Profile
    • Packaging the Distribution
    • Summary

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.

 

Code Downloads

Download the code and support files for this book.


Submit Errata

Please let us know if you have found any errors not listed on this list by completing our errata submission form. Our editors will check them and add them to this list. Thank you.


Errata

- 40 submitted: last submission 08 Aug 2012

Errata type: Technical | Page number: 0

Note on code indentation:
The author says ""I have attempted to make the code in the book adhere to the Drupal coding standards (http://drupal.org/coding-standards). I suggest that, in Chapter 1, developers use the Coder module to help keep code close to that standard. However, there is no prolonged discussion in the book of what the standards are. For that information, readers should visit http://drupal.org/coding-standards."

 

Errata type: code | Page number: 0

In the download code, modul philquotes code_example.zip: function _philquotes_get_quote() /query statement: ...type='quotes'...(plural) In the book the statement is: ...type='quote'... (singular). Correction: 'quote' is correct.

 

Errata type: Technical | Page number: 18

The book says JSON stands for JavaScript Over The Network. But it actually stands for JavaScript Object Notation.

 

Errata type: Typo | Page number: 19

Under "Developers' Tools" there is a line that reads "These tools are themselves provided by two modules, which can both can be obtained from the Drupal site." This sentence should not contain the second "can".

 

Errata type: Technical | Page number: 20

In the list of development environments, vi and Firebug are incorrectly capitalised as "VI" and "FireBug".

 

Errata type: Typo | Page number: 38

The first line of the first paragraph should be "This tool" instead of "This tools"

 

Errata type: Typo | Page number: 40

The first line of the comments for the _gooreads_fetch_bookshelf($url, > $num_items = 3) functions has bookshelf spelt wrong as bookshelp.

 

Errata type: Technical | Page number: 40

In the second paragraph, the given RSS URL is not working anymore. The new RSS URL is http://www.goodreads.com/review/list_rss/398385

 

Errata type: code | Page number: 45

The part of the code under the topic 'Processing the HTTP Results' should read:
if($doc === false) {
$msg = "Error parsing bookshelf XML for %url.";
$vars = array('%url => $url); watchdog('goodreads', $msg, $vars, WATCHDOG_WARNING);
return t("Getting the bookshelf resulted in an error"); }

 

Errata type: Code | Page number: 46

The $num_items variable is not used to limit the number of items displayed (as it should be). The code sample on page 46 (repeated on page 49) should have included this around line 6 of the function:
if ($count_items > $num_items) {
$items = array_slice($items, 0, $num_items, TRUE); }
Since the variable $len is not used, it can be removed.
Alternately, the foreach loop could be replaced with a for loop, which was the
original design. In this case, $len is used:
// foreach ($items as $item) { // Not used anymore for ($i = 0; $i < $len; ++$i) {
$item = $items[$i];
// ... rest of the code goes here
}

 

Errata type: code | Page number: 57

In the code sample at the top of the page, default values for the $author and $title variables are left empty. They should have been set to 'Unknown' and 'Untitled', respectively. The correct code appears on page 49 and again on page 51 (where it is explained).

 

Errata type: Code | Page number: 47

There is a wrong line of code. It says "if (empty($link)) !== 0) $link = $default_link;" it should be "if (empty($link)) $link = $default_link;"

 

Errata type: Code | Page number: 49

The $num_items variable is not used to limit the number of items displayed (as it
should be). The code sample on page 46 (repeated on page 49) should have included
this around line 6 of the function:
if ($count_items > $num_items) {
$items = array_slice($items, 0, $num_items, TRUE); }
Since the variable $len is not used, it can be removed.
Alternately, the foreach loop could be replaced with a for loop, which was the
original design. In this case, $len is used:
// foreach ($items as $item) { // Not used anymore for ($i = 0; $i < $len; ++$i) {
$item = $items[$i];
// ... rest of the code goes here
}

 

Errata type: Typo | Page number: 52

In the first line of the fourth paragraph, it should be "That string is then added to $out." instead of "That string is then added to $output."

 

Errata type: Typo | Page number: 61

In the middle of the page 'labotomy' is misspelled in code block, it should be spelled 'lobotomy'

 

Errata type: Typo | Page number: 63

The first sentence on page 63 which reads, "In this book, we will use only of the PHPTemplate engine for the following reasons:", is grammatically wrong. The sentence should not contain "of".

 

Errata type: Typo | Page number: 68

The fourth paragraph has the sentence, "In our case, we are extending a theme that we did not create. Clearly, we would do best to put our MODULE in the drupal/sites/all areas." The word module should be theme.

 

Errata type: Code | Page number: 71

Right after the sixth line of code at the top of the page "background-color: white;" should be a line that is missing "float: right;".

 

Errata type: Code | Page number: 72

The current code says:
stylesheets[all][] = style.css
stylesheets[all][] = new.css
Should be like this:
stylesheets[all][] = descartes-style.css
stylesheets[all][] = new.css
Otherwise the subtheme will not inherit style.css from bluemarine.

 

Errata type: Technical | Page number: 79

Last paragraph refers to "one for the right region" for two column layout, should refer to "left region"

 

Errata type: Language | Page number: 79

In the NOTE "CSS and the left and right regions" there is a line which reads "We styled these while developing our CSS-only theme earlier", it should read "We styled these while developing our CSS theme earlier"

 

Errata type: Technical | Page number: 79

The author has written "sell" instead of "cell" in the paragraph after code:- Each "sell" corresponds to a region: left, content, and right.

 

Errata type: Technical | Page number: 81

The first line should read: "If we look at the home page", not "if we look at the site".

 

Errata type: Technical | Page number: 85 | Errata date: 18 Dec 08

The second sentence in the second-to-last paragraph begins:
Invoking theme('images', $a, $b) causes...
It should read:
Invoking theme('image', $a, $b) causes...

 

Errata type: Typo | Page number: 87

The first word of the first sentence after the css script should "The" and not "These"

 

Errata type: Technical | Page number: 88

In the section "template.php Gotchas", it is written that you can override a function only once. The function 'phptemplate_breadcrumb()' has been used as an example. However, it is not true; use the function 'descartes_breadcrumb()' instead.

 

Errata type: Code | Page number: 101

The code on page 101 was written to exhibit the basics of Drupal DB code. However, it could be rewritten to take advantage of more specialized aspects of the database API. Instead of using a LIMIT clause in the SQL (which is not portable across various databases), we should use the db_query_range() function. Since the returned entry will have no more than one row with one column, we could use db_result() instead of db_fetch_object(). In the example, that will return the NID (Node ID).

 

Errata type: Code | Page number: 106

The code sample at the top of the page should be,
return array(
'theme_a' => array(/* settings */),
'theme_b' => array(/* settings */),
'theme_c' => array(/* settings */),
);
All three lines should end in commas instead of semicolons.

 

Errata type: Technical | Page number: 113

In the fifth paragraph, "philqyotes" should be "philquotes".

 

Errata type: Code | Page number: 114

stylesheet[all][] = philquotes.css
should be stylesheets[all][]

 

Errata type: Technical | Page number: 134

In the paragraph starting with "Note that the registered..." in one of the parentheses you have "http://localhost/drupal/q=philquotes.json" this should be "http://localhost/drupal/?q=philquotes.json" notice the question mark.

 

Errata type: Code | Page number: 167

In the code example, the method 'emailusers_mail' states:
$my_account = user_current_load(null);
it should be:
$my_account = user_load(null);

 

Errata type: Code | Page number: 167

In the code snippet, the method named 'user_current_load()' should be 'user_current_self()'

 

Errata type: Code | Page number: 173

In the hook_mail_alter() implementation, the $message['body'] .= t($append, $args);
only works if you don't have an array for the message body already only a single string. The solution is either:
1. Append the disclaimer to the end of the message array by using
$message['body'][] = t($append, $args);
In this case the hook_mail implementation also needs to create bodies as such by using:
$message['body'][] = $params['body'];
2. Use the $message[id] variable inside the hook_mail_alter to make sure we're only appending the disclaimer to messages generated by our own module and not append it to every single outgoing mail.

 

Errata type: Code | Page number: 196

There is a typo in the code comment. It reads "Existing files: title ...". It should read "Existing fields: title..."

 

Errata type: Code | Page number: 197

There is a typo in the code. "#maxlengh" should be "#maxlength"

 

Errata type: Technical | Page number: 209

The update function doesn't work that way. There must be a Top of Form _submit function which gets the form and form_state parameter. Form has the new values, form_state the old values, but later in the drupal code, form_state is used to rebuild the node information before update is called. In the submit function one has to store the changed fields into the form_state array.

 

Errata type: Code | Page number: 239

In the fifth paragraph and comments of the example function reference, 'hook_filter_info()' should be 'hook_filter_tips()'.

 

Errata type: Technical | Page number: 269

In the code demonstrating the original document it says {{report name}}, it should be {{brief name}}.

 

Errata type: Technical | Page number: 269

In paragraph 6 it talks about the footer added by philquotes_mail_alter() which should be emailusers_mail_alter()

 

Sample chapters

You can view our sample chapters and prefaces of this title on PacktLib or download sample chapters in PDF format.

Frequently bought together

Learning Drupal 6 Module Development +    FL Studio Cookbook =
50% Off
the second eBook
Price for both: $40.05

Buy both these recommended eBooks together and get 50% off the cheapest eBook.

What you will learn from this book

  • A developer's overview of important Drupal concepts and APIs, like nodes, menus, and forms
  • Using Drupal tools for module development
  • Creating a new module from scratch
  • Harnessing the power of the Drupal hook system
  • Using key Drupal functions
  • Creating custom content types, from basic to advanced
  • Performing database operations
  • Writing module installers and uninstallers
  • Making Drupal content available to JavaScript with a JSON service
  • Interacting with the theme system to build crisp layouts
  • Creating richer user interfaces with Drupal's JavaScript libraries
  • Working with blocks, nodes, actions, and menus
  • Using a web service to retrieve and display XML data
  • Creating an administration interface
  • Customizing user profiles
  • Writing actions and triggering them with events
  • Working with the Forms API
  • Defining custom hooks and making modules work together
  • Exploring the database and schema API
  • Creating an installation profile to bundle your modules into a custom Drupal distribution

In Detail

With great power comes... tremendous flexibility. Drupal is an award-winning open-source Content Management System, and the feature-packed sixth release is right around the corner. It's a modular system, with an elegant hook-based architecture, and great code. These are a few of the perks that make Drupal a choice platform for developers who want the power of an established CMS, but the freedom to make it work for them. From social networking to AJAX to e-commerce, the hundreds of existing modules attest to Drupal's flexibility. When you create a new module for Drupal, it fits seamlessly into the look and feel of your overall site. If you can think it in PHP, you can code it as a Drupal module.

Dive into Drupal module development as we create the Philosopher Biographies website, developing new modules and themes to meet practical goals. Create custom content types. Add AJAX functionality with the jQuery library. Use external XML APIs to add content to your site. Email newsletters to site members. Use themes. Empower administrators with extra features. And bundle it all up in a custom installation profile. You won't find a "hello world" here!

If you're eager to start creating modules for Drupal 6, this is your book. Walk through the development of complete Drupal modules with this primer for PHP programmers. Specifically written for Drupal 6, this book will get you coding modules as quickly as possible, and help you add the features that will give your work that professional gloss!

Just getting started with Drupal development? This book will give you a clear, concise and, of course, practical guidance to take you from the basics of creating your first module to developing the skills to make you a Drupal developer to be reckoned with.

Are you a Drupal developer looking to update to version 6? This book covers the new and updated APIs to guide your transition to Drupal 6. The new menu system, the Forms and Schema APIs, and many core revisions are covered in this book.

Walk through the development of complete Drupal 6 modules with this primer for PHP programmers, written specifically for Drupal 6 to get you started coding your first module.

Are you a Drupal developer looking to update to version 6? This book covers the new and updated APIs to guide your transition to Drupal 6. The new menu system, the Forms and Schema APIs, and many core revisions are covered in this book.

 

Approach

Who this book is for

This book is written for PHP developers who want to add custom features to Drupal. You will need to know the basics of PHP and MySQL programming, but no experience of programming Drupal is required, although you will be expected to be familiar with the basic operation of Drupal.

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software