Start learning with our library of video tutorials taught by experts. Get started

Drupal 7 Custom Module Development

Creating your first module


From:

Drupal 7 Custom Module Development

with Jon Peck

Video: Creating your first module

Drupal looks for modules in several places. While it may be tempting to put a contributed or custom module in the modules directory of the site root, this directory is reserved for Drupal core modules. Instead, additional modules are typically stored within the sites > all > modules directory of the web root. If you have installed contributed modules, you may see some directories there now. Best practice is to organize modules within subdirectories with clear headings, such as contrib and custom.

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Drupal 7 Custom Module Development
2h 57m Advanced Oct 16, 2012

Viewers: in countries Watching now:

Extend your Drupal 7 sites with custom modules, which allow you to create everything from admin interfaces to forms. Author Jon Peck describes how modules extend your base Drupal installation, then walks through how to write your own module with a practical example featuring geo-positioned alternative energy centers. The course also describes how to control access to site features, create new content types, build forms, understand data persistence, embrace coding standards, and much more.

Topics include:
  • Creating your first module
  • Interacting with hooks
  • Working with permissions and roles
  • Controlling access
  • Adding a menu item to an admin interface
  • Using the Form API (FAPI) to quickly create a form
  • Creating custom form validation
  • Manually creating a custom content type
  • Validating user input
  • Importing content using feeds
  • Creating a block
  • Understanding best practices and coding standards
Subjects:
Developer Web CMS Blogs Web Design Programming Languages Web Development
Software:
Drupal
Author:
Jon Peck

Creating your first module

Drupal looks for modules in several places. While it may be tempting to put a contributed or custom module in the modules directory of the site root, this directory is reserved for Drupal core modules. Instead, additional modules are typically stored within the sites > all > modules directory of the web root. If you have installed contributed modules, you may see some directories there now. Best practice is to organize modules within subdirectories with clear headings, such as contrib and custom.

Contrib is short for contributed modules, which I previously mentioned, and custom is for custom modules, which I will be demonstrating. Each Drupal module has a human readable name and a machine name. The machine name is used throughout the module development, while the human readable name is only shown on administrative interfaces. Drupal module machine names follow a consistent naming convention. All lower case, no spaces, and concise as possible. You can use underscores in the module name, but it can get unwieldy if you have more than one.

Numbers are allowed, but are generally not recommended as a best practice. As the module name is also used in function names, module names cannot start with a number. Here are some good examples of naming conventions. These are real contributed modules available on drupal.org. Coder, a module for algorithmically assisting with code review, devel, which is development and collection of debugging tools, and google_analytics, which is a helper for adding a Google Analytics code to a website.

Next, some examples that are technically legal but are not recommended for various reasons; these module names are imaginary. Test1, it's a legal name but does not clearly describe the purpose of the module. A number should be avoided as well. Canoper_2, it's a legal name but it contains a specific version number. Cat_and_dog_administration_assistant _program, legal, but too verbose. Finally, some bad module names.

Again, these modules do not exist; MyModule with a capital M for both. The upper case and camel case are not appropriate for module names. Test with a capital T space Module, the spaces are not allowed and it starts with a capital letter. 2good; similar to PHP methods and functions, module names cannot start with a number. The first step in module creation is describing the module to Drupal. Instead of describing module metadata in a function which can have a lot of overhead and dependencies, the metadata is described in the PHP INI format.

The INI format is a very simple and widely used configuration formats which can be read directly from the file system. The metadata is stored within an .info file. The name refers to the naming convention and the file extension. A .info file consists of a module machine name followed by a period and the file extension info. For the purposes of the demonstration, I will develop a module to facilitate the management of a database of Wind Farms. A concise way of describing the module would be Wind Farms, which I will combine into one word, to keep the machine name simple.

I'm going to create the .info file for the module. Within the IDE or text editor, navigate to the directory's sites > all > modules, right-click on modules, and go to New > Other, select Other, then Empty file. File Name, this is the machine name for the module. So the filename should be windfarms.info. Remember, it's best practice to place all custom modules in a subdirectory called custom, then the module itself is contained in a folder with the same machine name.

Under Folder specify a subdirectory, /custom/ windfarms, then click Finish to create the file. .info files consist of a simple series of directives. Each directive contains a name, an equal sign for assignment, and a value. You can also place comments within .info files. Any line that begins with a semicolon is ignored by the Drupal INI Parser. I'm going to describe the windfarms module with only three required directives: name, description, and core.

The first directive to create is the name of the module. As the machine name is already specified in both the folder and the .info file, there is no need to explicitly declare it. However, the module must be able to be managed from the Drupal user interface, so human readable name needs to be assigned. The name directive can be created with the following syntax, name = Wind Farms. Next, a description is needed. This should be a single plain text description in one sentence that describes the purpose of the module; description = A database of wind farms.

Finally the core directive. This specifies the major version of Drupal that is required for this module. There is no need to specify particular minor version of Drupal, so the version wildcard x is used; core = 7.x, save the .info file. At this point the module is described to Drupal. However, if I open a browser and go to the Drupal module list, you will not see the module listed anywhere. One final component is still needed, a .module file.

A .module file is just a PHP file with a different file extension. This is the dynamic heart of the module that by convention contains all the major implementations of Drupal functionality. For the time being this file can be empty. In the IDE, right-click on the windfarms directory and go to New > Empty File, and name it windfarms.module, Finish to create the file. As this is a PHP file, open a new PHP code tag, but do not close it.

According to the Drupal coding standard, the closing PHP code tag is purposely omitted from the module and include files. This is done for several reasons; it eliminates the possibility of unwanted whitespace at the end of a file from causing header errors, XML validation issues and other similar problems. The closing delimiter is optional in PHP and php .net itself does not use closing delimiters. Therefore, the closing PHP tag can be omitted. Even though this file can be empty for now, Drupal coding standards dictate that each file has standardized comments containing documentation, also known a docblock at the beginning of the file.

These docblocks are formatted using the doxygen format, which is used by a document generator of the same name. To create a file level docbock, type forward slash followed by two asterisks then type Enter. Some IDs will automatically create a standard docblock, if not, indent one space and add a new asterisk followed by a space. Each file level docblock starts with a token @file on its own line. This indicates to the documentation parsers and people who are reading the source code that this documentation block contains a description of the contents of this file.

On the next line, still within the comment block, describe in a high level sentence the purpose of the module. In this case, Custom functionality for a wind farm database. If the comment block is not closed beneath, do so now. Finally, add a new line to the end of the file. This is considered a best practice and conforms the Drupal coding standard in order to make patches easier to read. Save the module, then go to the browser and click on Modules, scroll down to Other and the newly created Wind Farms module will be listed.

Note that there is no version or operations available and that the module is not enabled by default. There is no need for operations at this time, but not knowing the version of a module is not very helpful. When a module is packaged and available on drupal.org, the version is automatically added by the source control system. As this module is being developed outside drupal.org, the version will need to be manually specified. Return to the IDE and open the .info file.

The module version can be specified with the name version, followed by the assignment operator. The version itself should start with a core version of Drupal, which in this case is 7.x followed by a hyphen, then the module version in point format. Do not use spaces or underscores for the version. I will call this version, 0.1, an additional optional label can be specified after the module version. There are several common naming conventions for optional labels; dev for development only, which is often volatile; alpha, which is the first phase of software testing; beta, which is feature complete, and RC for release candidate final testing.

The optional label is set with a dash followed by the label. As this module is under development, I will label it as -dev. Save the .info file and return to the browser and refresh. The Wind Farms module now shows a version. The new custom module has been described to Drupal and is now recognized. There is now a placeholder where custom functionality will be placed. In the next segment, I will provide an overview of Drupal's application programming interface known as hooks.

Find answers to the most frequently asked questions about Drupal 7 Custom Module Development.


Expand all | Collapse all
Please wait...
Q: gmap3_tools is not working the way I expected it to. What version of gmap3_tools should I be using?
A: Use the free exercise file containing the version of gmap3_tools used for recording; the published version of the module on drupal.org has changed since recording and is not backwards compatible.
Q: I attempted to run the Drupal site root from the project files, but the site isn't loading. Why not?
A: The Drupal configuration file in sites/default/settings.php contains database configuration specific to the environment used to record the movie. This may be different than your environment. Edit the file and search for "windfarms" - you may need to change the database host, username, password, db name and port to match your specific environment.
Share a link to this course
Please wait... Please wait...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.
Upgrade now


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

join now

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Drupal 7 Custom Module Development.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked