19
MASTER DRUPAL 7 MODULE DEVELOPMENT by blair wadman sample available for purchase at http://befused.com/master-drupal/

Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

  • Upload
    vonhi

  • View
    229

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

MASTER DRUPAL 7 MODULE DEVELOPMENTby blair wadman

sampleavailable for purchase at http://befused.com/master-drupal/

Page 2: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

LESSON 1INTRODUCTION

Page 3: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Master Drupal 7 Module Development 1

Lesson One - Introduction

In this section, you will be introduced to the core Drupal concepts required to develop

modules.

Goals

• Gain a basic understanding of core Drupal concepts like Nodes, Entities and

Forms API

Drupal Concepts included

• Nodes

• Comments

• Blocks

• Entities

• Hook system

• Menu and Routing

• Theme system

• Forms API

• Users

• Devel

• Drush

Drupal codeDrupal’s code is split into three main areas: core, contributed and custom.

Drupal CoreWhen you download Drupal, you are downloading Drupal core. It consists of a set of library files and core modules. It is relatively lean and provides the base level of functionality. The library provides a set of tools for interacting with database, form building, translating etc. The core modules are essential modules that cannot be turned off. Core modules include node, taxonomy and user modules.

Page 4: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 2

You might have heard the phrase Do not hack core before. This simply means, do not change any of the core code. In Drupal, if you want to add functionality, or change the way Drupal behaves, you do this either by downloading a contributed module or creating your own custom module.

Contributed ProjectsDrupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge variety in extra functionality. Contributed modules are developed by Drupal developers who are “contributing” back to the community. They maintain, develop further and deal with the issue queues on a voluntary basis. This forms an important part of the essence of the Drupal community.

Custom ModulesA custom module is a module that you (or your team) have developed yourself. It may become a contributed module if you make it generic enough so that it is not tied to your specific instance of Drupal.

Drupal StructureWhen you download Drupal, you will find all the folders and files shown below, with the exception of sites/all/modules and sites/all/themes. You have to create those manually.

Page 5: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 3

Figure 1-1: Drupal files and folders

Page 6: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 4

Folder/File Type Description includes folder Library of common functionsmisc folder Javascript, icons and imagesmodules folder Core modulesprofiles folder Installation profilesscripts folder Various scripts for syntax checking etcsites folder Contributed & custom modules, themes, settings themes folder Default themes and template enginescron.php file Runs periodically for specific tasksindex.php file Entry point for all requestsinstall.php file Installer filerobots.txt file Robot exclusion standard, used to instruct search engines

update.php file Run to update the database during Drupal core and module updates

xmlrpc.php file Receives XML-RPC requestsTable 1-1: Description of main files and folders

As you can see, modules other than core modules go inside the sites folder. You will probably see variations on this in other books and online, but the pattern of sites/all/contrib and sites/all/custom is one that I have seen the most success with on real projects.

A note on multi-sitesDrupal has the ability to run more than one website from the same code base. This is known as a multi-site. If you are running a multi-site, you would create a folder per site inside the sites folder. For example, if your site was called example.com, you would create a folder inside sites called example.com. Inside that folder, you would create a folder for modules, themes and files. It would also contain a settings file. Any modules and themes that relate to all sites running off this code base live in sites/all.

NodesIn Drupal, a node is a primary piece of content. When you create content in Drupal, you are in fact creating a new node.

Page 7: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 5

Figure 1-2: Add content

If you view that content at its URL, you are viewing the full node.

Figure 1-3: Viewing full node

Different types of nodes can be created. These are often referred to as content types.

Page 8: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 6

Each content type can have its own set of fields. For example, you could have a Blog post content type, with title and body and an Image content type with title and image field.

Nodes are stored in the node table in the database and this is one of the most important tables. Each node has a unique ID called the Node ID, or nid for short. When you view a Drupal page, even if you are using an alias, you are actually calling node/nid. For example, the first node will be node/1.

When developing modules, it is important to understand the node object. The node object contains all of the important information about a particular node. If you know the node ID, you can get the node object by calling node_load(), as follows:

$node = node_load($nid);

We will talk more about this when you start developing your own module.

CommentsComments are generally attached to nodes and are an integral part of encouraging user engagement. In its simplest form, comments can be made against blog posts. But it does not end there. The Drupal Forum module is actually a collection of nodes and comments. Each topic is a node and replies are comments.

Page 9: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 7

Figure 1-4: A comment attached for a simple node

BlocksA block is a secondary piece of content that is usually displayed in regions around the main content, such as the header, sidebars and footer.

Common examples of blocks• Navigation menu• Search form• Logo• Copyright message

You might occasionally come across a grey area where you are not sure if a particular piece of content should be defined as a block or a node. As a general rule of thumb, if a piece of node is meant to be displayed on multiple pages (not necessarily every page), it probably should be a block.

Page 10: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 8

Figure 1-5: Blocks

Entities, Fields and BundlesEntities, Fields and Bundles are all new to Drupal 7.

Entities provide a mechanism to create types of data that are not nodes. In times past, you might hear developers saying “everything is a node”. This no longer holds true. Nodes, comments, taxonomy and users are all types of entities that come with Drupal. You can create your own entities and some contributed Drupal projects come with their own. For example, Drupal Commerce defines its own entities such as Product entity, Customer profile entity, Line item entity, Order entity and Payment transaction entity. In these examples, using a simple Node entity would have been too restrictive.

Fields are re-usable pieces of content which can have validators, widgets and formatters.

Page 11: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 9

A bundle is a sub-type of an entity and you can attach fields to it. An example of a bundle is an Article, which is a subtype of the node entity. This is similar to a content type in Drupal 6.

To illustrate the concept of entities,bundles and fields, take a look at the illustration below. This is an example of the node entity which contains two bundles, Article and Gallery. Article has two fields, title and body. Gallery has three fields, title, image and summary.

node

article gallery

title

body

title

image

summary

entity

bundle

field

bundle

field

field

field

field

Figure 1-6: Entity, bundles and fields

Comparison to Drupal 6Fields and bundles are closely related to CCK in Drupal 6. An Article would be a content type in Drupal 6 and it would have fields attached to it.

Request and ReponseWhen a user requests a page on a Drupal site, a lot happens behind the scenes to generate that page. The following illustration is a summary of the steps Drupal goes through to generate a node page.

Page 12: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 10

Theme system- format & style data

HTML & CSS

Node Module- load node

Bootstrap- load libraries & initialise Drupal

Menu System- decide how to handle path- does user have access?- map to callback function

Request

Response

Figure 1-7: Request and response process

Hook systemThe hook system is central to Drupal. Pretty much anything and everything that happens in Drupal happens because of a hook.

During the request and response lifecycle, Drupal and modules fire off events and listens for a response through its hook system. It checks all enabled modules and looks

Page 13: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 11

for functions that follow certain patterns. For example, if it is checking for blocks, it checks all modules with the <modulename>_block(). After finding these functions, Drupal executes them and uses the data they return as part of the response to the page request.

You can listen for an event by calling a specific function, and then adding something that will happen when that event is fired. Let’s take another look at the Drupal request and response process with hooks added in.

Theme system- format & style data

HTML & CSS

Node Module- load node

Bootstrap- load libraries & initialise Drupal

Request

hooks

hooks

hooks

hooks

Response

Menu System- decide how to handle path- does user have access?- map to callback function

Figure 1-7: Request & response & hooks

ExampleThe best way to understand this is by way of an example. A user logs on the website.

Page 14: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 12

The act of logging in is an event. You can call a function called hook_user_login() in your module which will listen for this event. You add some code to display a hello message if a particular user logs in.

Userlogs in

Displaymessage

hook

hook_user_login

Figure 1-8: Hook user login example

Modules can either define or implement a hook.

Implementing hook: A hook has been defined by another module and you are implementing it. In our previous example, we implemented hook_user_login(). hook_user_login() is defined by the User module. In most cases, you will be implementing a hook.

Invoking a hook: When you write a module, you can define a new hook. By doing so, you are allowing other modules to implement the hook and further extend functionality.

Page 15: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 13

Menu & RoutingThe Drupal menu system is one of the most import concepts to understand in order to develop Drupal modules.

The menu system handles 3 areas:1. Callback mapping (menu router)2. Access control3. Menu customisation

Menu Router & Callback MappingYou were introduced to hooks in the previous section. Like most of Drupal, the Menu System uses hooks. One of the most important parts of the Menu System for module development is hook menu (hook_menu()). Hook Menu is a function that we use to define menu items and callback functions. hook_menu() allows your module to register paths and information on how it will handle requests to that path.

The second step on Figure 1-7 (Request and Response) is the Menu System. If it wasn’t for the Menu System, Drupal would not know what to do with a request for a URL. The Menu system decides what to do with the path and which callback function to fire.

Access ControlWhen handling a request, the menu system must decide if the user has the necessary permission to view the content being requested.

Menu CustomisationThe menu system also helps with the structure of a Drupal site through menus. Menus are hierarchical and a menu item can have any number of children.

Figure 1-9: Example of a menu, the navigation menu

Page 16: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 14

Theme SystemThe Theme System controls the display and presentation (look and feel) of content. The theme system is not confined to just themes. Core libraries, modules and themes all make up the theme system. The core library initialises themes and locates theme functions and templates to use. Modules can define default theming for the content that it is responsible for. A theme can then override that theming.

Figure 1-10: Files included with the bartik theme

Templates for content typesOne of the templates that you can use is node-content_type.tpl.php. That is a node template that is specific to a particular content type. For example, if we had a content type called blog_post, the template file would need to be called node-blog_post.tpl.php. In theory, this file could exist in either the theme, or in the module that creates and controls the content type. It is quite common for content types to be created in the Drupal UI (CCK in Drupal 6, Fields in Drupal 7) and not controlled by a module. In those cases, the templates tend to reside in the theme layer.

We are focusing on module development in these lessons, so we will not cover developing in the theme itself. However, theming in the module will be included.

Render ArraysDrupal’s theme system uses render arrays to generate HTML pages. This system allows module developers or themers to change the page content or layout before it is

Page 17: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 15

displayed to the user. When creating a render array, you create a simple array with a defined set or properties. Properties include a prefix, suffix and markup. Drupal takes these arrays and converts them into raw HTML to return to the browser. Do not worry at the moment if this does not make sense, it will be easier to understand when you implement it for yourself in a later lesson.

Forms APIForms are an essential part of most websites, and Drupal websites are no exception. They are the primary method for users to submit data to the website, whether it be to login, comment on an article or create a new article. In Drupal module development, you use the Form API to define a form. Drupal then builds the form, displays it, validates it and collects the data.

By using an established API and using it correctly, we are going a long way towards protecting our application against a whole range of possible security vulnerabilities. It also takes advantage of the hook system. When you create a form, another developer can hook into your form and change it. And you can hook into any other form and change it. That is an amazing powerful feature.

There is an extensive list of elements/properties you can use on api.drupal.org1.

UsersA user can be anyone who visits a Drupal website. Some users are registered with the website and some are not. If a user is not registered with the website, they are called an anonymous user. A user who is registered is called an authenticated user.

Roles and PermissionsAuthenticated users may belong to one or more roles. A role is a set of permissions that all users who belong to it share. For example, a publishing website might have content editors who belong to the editor role. The editor role might have permission to add and edit nodes of a certain type. All users who belong to the editor role will have that permission.

ProfileEach user can have a profile and a profile can have any number of fields.

User ObjectUser data is stored in the database and is available in the user object.

Drupal as a social networkMany people think of Drupal as a CMS. It can be a CMS, but it can also be a lot more than that. Drupal’s User system lends itself very well to that of a social network and it is not uncommon for developers to build quite advanced social networks in Drupal.

Page 18: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 16

DevelThe Devel module is an essential part of a Drupal developer’s toolbox. It includes a range of tools designed to make developers’ and themers’ lives easier. When you get more experienced with module development, you will probably use it for things like identifying slow database queries. But at this stage, we will use it for one really simple time saver - Drupal Print Message. Give it an array or object and Drupal Print Message will enable you to visually walk through its data in a message on the page.

As an example, consider this simple array:

$diet = array(pizza, fruit, beer, water, toast);dpm($diet);

This will print out the following:

Figure 1-11: Devel dpm

This is a very simple example. When you start developing modules, you will have to deal with some large arrays and objects, such as the node object. Visually walking through them will help you pin point that data that you need.

DrushDrush is a command line utility for Drupal. It provides developers with the ability to manage a Drupal installation from the command line, rather than having to always use the Drupal admin interface. Once you get used to it, it can be a real time saver. You will be using Drush through this book.

SummaryIn this section, you were introduced to some of the key Drupal concepts that are required for developing modules. It is a very high level explantation and you will be exposed to the technical implementation of these in the remaining lessons.

1 Form API elements and properties http://api.drupal.org/api/drupal/developer%21topics

Page 19: Master Drupal 7 Module Development - befused.com · Drupal core is extended via contributed modules and themes. There are thousands of modules on drupal.org and they offer a huge

Lesson One - Introduction

Master Drupal 7 Module Development 17

%21forms_api_reference.html/7