Showing posts with label Modules. Show all posts
Showing posts with label Modules. Show all posts

Jun 27, 2012

How to create a module in Drupal 7.x

What is a module in Drupal?
A module is nothing but a collection of functions that links into Drupal, providing all the additional functionality/behaviour for your Drupal installation or your Drupal site. After reading this tutorial, you will be able to create a basic block module and use it as a template for more advanced modules.


Things to be remember before we start:
This tutorial will not necessarily prepare you to write modules for public release it will only give you a step by step integration reagarding "How to create a module!". It does not cover caching, nor does it elaborate on permissions or security issues but you can simply use this tutorial as your starting point and extend your skills with other resources.


Our tutorial assumes you have:



  • Basic PHP knowledge, including syntax and the concept of PHP objects

  • Basic understanding of database tables, fields, records and SQL statements

  • A working Drupal 7 installation

  • Drupal administration access

  • Webserver access


Our tutorial does not assume you have any knowledge about the inner workings of a Drupal module.


Getting started


In this tutorial we'll create a module that lists links to content such as blog entries or forum discussions that were created recently (within the last week). This page in the tutorial describes how to create the initial module file and directory.


Name your module


The first step in creating a module is to choose a "short name" for it. This short name will be used in all file and function names in your module, so it must start with a letter, and it must contain only lower-case letters and underscores. For this example, we'll choose "current_posts" as the short name. Important note: Be sure you follow these guidelines and do not use upper case letters in your module's short name, since it is used for both the module's file name and as a function prefix. When you implement Drupal "hooks" (see later portions of tutorial), Drupal will only recognize your hook implementation functions if they have the same function name prefix as the name of the module file.


It's also important to make sure your module does not have the same short name as any theme you will be using on the site.


Create a folder and a module file


Given that our choice of short name is "current_posts" :



  1. Start the module by creating a folder in your Drupal installation at the path:

    • sites/all/modules/custom/current_posts



  2. Create the PHP file for the module :

    • Save it as current_posts.module in the directory sites/all/modules/custom/current_posts

    • As of Drupal 6.x, sites/all/modules is the preferred place for non-core modules (and sites/all/themes for non-core themes), because this places all site-specific files in the sites directory. This allows you to more easily update the core files and modules without erasing your customizations. Alternatively, if you have a multi-site Drupal installation and this module is for only one specific site, you can put it in sites/your-site-folder/modules.



  3. Add an opening PHP tag to the module :


    • <?php


    • Module files begin with the opening PHP tag. Do not place the CVS ID tag in your module. It is no longer needed with drupal.org's conversion to Git. If the coder module gives you error messages about it, then that module has not yet been updated to drupal.org's Git conventions.




The module is not operational yet: it hasn't been activated. We'll activate the module later in the tutorial.


Coding standards


As per the Coding standards, omit the closing ?> tag. Including the closing tag may cause strange runtime issues on certain server setups. (Note that the examples in documentation will show the closing tag for formatting reasons only and you should not include it in your real code.)


Telling Drupal about your module


All modules must have a 'modulename.info' file, which contains meta information about the module.


The general format is:


[php]name = Module Name<br />
description = A description of what your module does.<br />
core = 7.x[/php]



For our module, we will replace 'Module Name' in the example above with the name of our module, 'Current Posts'. Without this file, the module will not show up in the module listing. Here is our specific example:


[php]name = Current Posts<br />
description = A block module that lists links to recent posts.<br />
core = 7.x[/php]



Add the source above to a file named current_posts.info and save it into the module's directory at sites/all/modules/current_posts.


Note: If you copy and paste this code block, ensure that the description data does not contain a line break (turn off word-wrap on your text-editor to be sure). Otherwise, the .info file will not parse correctly.


.Info File Details


The details of what to put in a .info file can be found on the Writing .info files page.


Comments in Drupal modules


It's always a good idea to document how your module works in comments. Drupal uses Doxygen to draw documentation from source code, so contrib modules on drupal.org follow strict comment guidelines. See Doxygen and comment formatting conventions for more details. Following these guidelines is beneficial to anyone looking at your code even if it's not strictly necessary for your situation.


Your first comment:


[php]&lt;?php<br />
/**<br />
* @file<br />
* A block module that displays recent blog and forum posts.<br />
*/<br />
?&gt;[/php]



@file signifies that this comment pertains to the entire file. The doc block begins with a slash and two asterisks (/**) and ends with one asterisk and a slash (*/). Following Drupal guidelines, we will introduce each function in the module with such a comment.


Implementing your first hook


Hooks are fundamental to Drupal modules. They allow you to integrate your module into the actions of Drupal core.


[php]&lt;?php<br />
&lt;div&gt;<br />
&lt;pre&gt;function current_posts_help($path, $arg) {</p>
<p>}<br />
?&gt;[/php]


 


[php]&lt;?php<br />
/**<br />
* Implements hook_help.<br />
*<br />
* Displays help and module information.<br />
*<br />
* @param path<br />
*   Which path of the site we're using to display help<br />
* @param arg<br />
*   Array that holds the current path as returned from arg() function<br />
*/<br />
function current_posts_help($path, $arg) {<br />
switch ($path) {<br />
case &quot;admin/help#current_posts&quot;:<br />
return '&lt;p&gt;'.  t(&quot;Displays links to nodes created on this date&quot;) .'&lt;/p&gt;';<br />
break;<br />
}<br />
}<br />
?&gt;[/php]


(Note the closing ?> should not appear in your code.)


Declaring the block


To use this hook to define our block, go to your current_posts.module file and create the function current_posts_block_info() as follows:


[php]&lt;?php<br />
/**<br />
* Implements hook_block_info().<br />
*/<br />
function current_posts_block_info() {<br />
$blocks['current_posts'] = array(<br />
'info' =&gt; t('Current posts'), //The name that will appear in the block list.<br />
'cache' =&gt; DRUPAL_CACHE_PER_ROLE, //Default<br />
);<br />
return $blocks;<br />
}<br />
?&gt;[/php]



(Remember not to include the closing ?> in your code.)


Retrieving data


The function begins with getting the time numbers. Here's the first part:


[php]&lt;?php<br />
/**<br />
* Custom content function.<br />
*<br />
* Set beginning and end dates, retrieve posts from database<br />
* saved in that time period.<br />
*<br />
* @return<br />
*   A result set of the targeted posts.<br />
*/<br />
function current_posts_contents(){<br />
//Get today's date.<br />
$today = getdate();<br />
//Calculate the date a week ago.<br />
$start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 7), $today['year']);<br />
//Get all posts from one week ago to the present.<br />
$end_time = time();<br />
?&gt;[/php]




Next we use Drupal's Database API to retrieve our list of current nodes. This is the second part of the custom function:


[php]&lt;?php<br />
//Use Database API to retrieve current posts.<br />
$query = db_select('node', 'n')<br />
-&gt;fields('n', array('nid', 'title', 'created'))<br />
-&gt;condition('status', 1) //Published.<br />
-&gt;condition('created', array($start_time, $end_time), 'BETWEEN')<br />
-&gt;orderBy('created', 'DESC') //Most recent first.<br />
-&gt;execute();<br />
return $query;<br />
}<br />
?&gt;[/php]



  1. We build the query using the db_select method, which takes a table name ('node') and alias ('n') as arguments.

  2. The fields method uses the table assigned the alias 'n' to select the fields listed in the array in the second argument.

  3. The condition method takes three arguments. The first is the field, the second the value, the third the operator. If no operator is specified, as in 'status' above, = is assumed.

  4. The orderBy method sorts according to the field in the first argument, in the order specified by the second argument.

  5. The execute method compiles and runs the query and returns a result set/statement object.


Here's the complete function:


[php]&lt;?php<br />
/**<br />
* Custom content function.<br />
*<br />
* Set beginning and end dates, retrieve posts from database<br />
* saved in that time period.<br />
*<br />
* @return<br />
*   A result set of the targeted posts.<br />
*/<br />
function current_posts_contents(){<br />
//Get today's date.<br />
$today = getdate();<br />
//Calculate the date a week ago.<br />
$start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 7), $today['year']);<br />
//Get all posts from one week ago to the present.<br />
$end_time = time();</p>
<p>//Use Database API to retrieve current posts.<br />
$query = db_select('node', 'n')<br />
-&gt;fields('n', array('nid', 'title', 'created'))<br />
-&gt;condition('status', 1) //Published.<br />
-&gt;condition('created', array($start_time, $end_time), 'BETWEEN')<br />
-&gt;orderBy('created', 'DESC') //Most recent first.<br />
-&gt;execute();<br />
return $query;<br />
}<br />
?&gt;[/php]



(Remember not to include the closing ?> in your code.)


Generating block content


Access check


Here's the first part of the code:


[php]&lt;?php<br />
function current_posts_block_view($delta = '') {<br />
switch($delta){<br />
case 'current_posts':<br />
$block['subject'] = t('Current posts');<br />
if(user_access('access content')){<br />
//Retrieve and process data here.<br />
}<br />
?&gt;[/php]






Coding the data as links


Here's the next bit of code:


[php]&lt;?php<br />
//Use our custom function to retrieve data.<br />
$result = current_posts_contents();<br />
//Array to contain items for the block to render.<br />
$items = array();<br />
//Iterate over the resultset and format as links.<br />
foreach ($result as $node){<br />
$items[] = array(<br />
'data' =&gt; l($node-&gt;title, 'node/' . $node-&gt;nid),<br />
);<br />
}<br />
?&gt;[/php]






Theming the data


Here's the last section of code for current_posts_block_view:


[php]&lt;?php</p>
<p>if (empty($items)) { //No content in the last week.<br />
$block['content'] = t('No posts available.');<br />
} else {<br />
//Pass data through theme function.<br />
$block['content'] = theme('item_list', array(<br />
'items' =&gt; $items));<br />
}<br />
}<br />
}<br />
return $block;<br />
}<br />
?&gt;[/php]





The Final Steps


Testing and troubleshooting the module


It's time to enable and fully test your module!


Enable the module


Go to Modules, or http://example.com/admin/modules, and scroll down to the bottom of the list in the 'Other' category. You should see the module 'Current posts.' Click the checkbox to enable Current posts, and save your configuration. Now you should see a link to Help beside the module name. Click it to see the help text you entered in current_posts_help.


Enable the block


Next, navigate to Structure > Blocks, or http://example.com/admin/structure/block. Scroll down to the bottom of the list. Among the disabled blocks, you should find the name, 'Current posts'. Set its location for one of the page regions and save. Navigate to another page like your homepage to see your block. Congratulations! You have written a working module.


Troubleshooting


If you get a "white screen" or a PHP error when you enable this module, it probably means you have a syntax error in your .module file. Be sure all your punctuation is correct, semi-colons, commas, etc. all in the right places, and that you have all the hook names and module short names spelled correctly. (In the case of a white screen, you may be able to find out what the PHP error was by looking in your Apache error log. Or you can try changing PHP's error reporting level.)


If you cannot find and fix the syntax error, nothing on your site will display, because Drupal will try to load your module on every page request. The easiest way to get your site working again is to delete the module's folder or move it out of the site, in which case Drupal will figure out that it shouldn't load this module after all, and your site should work again.


Clear caches


Drupal caches a lot of data, and if you are not seeing changes appear, that could be why. In this phase of the module, the caches shouldn't be an issue, but they will be as we proceed. To get all the troubleshooting instructions in one place, we'll give you the instructions here that you'll need later.


To clear the caches, go to Configuration > Performance or http://example.com/admin/config/development/performance, and click the Clear all cachesbutton.

May 16, 2012

20+ most installed modules of Drupal

There are more than thousands of contributed Drupal modules, but sometimes it's necessary for us to find out which is the most installed Drupal module that can be perfectly suitable for our project.

Below I've listed some of the most used/installed & essential Drupal modules:

Views


What is Views


The Views module provides a flexible method for Drupal site designers to control how lists and tables of content, users, taxonomy terms and other data are presented.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content.

Token


Tokens are small bits of text that can be placed into larger documents via simple placeholders, like %site-name or [user]. The Token module provides a central API for modules to use these tokens, and expose their own token values.

Note that Token module doesn't provide any visible functions to the user on its own, it just provides token handling services for other modules.

Pathauto


The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of/node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

Chaos tool suite (ctools)


This suite is primarily a set of APIs and tools to improve the developer experience. It also contains a module called the Page Manager whose job is to manage pages. In particular it manages panel pages, but as it grows it will be able to manage far more than just Panels.For the moment, it includes the following tools:

  • Plugins -- tools to make it easy for modules to let other modules implement plugins from .inc files.

  • Exportables -- tools to make it easier for modules to have objects that live in database or live in code, such as 'default views'.

  • AJAX responder -- tools to make it easier for the server to handle AJAX requests and tell the client what to do with them.

  • Form tools -- tools to make it easier for forms to deal with AJAX.

  • Object caching -- tool to make it easier to edit an object across multiple page requests and cache the editing work.

  • Contexts -- the notion of wrapping objects in a unified wrapper and providing an API to create and accept these contexts as input.

  • Modal dialog -- tool to make it simple to put a form in a modal dialog.

  • Dependent -- a simple form widget to make form items appear and disappear based upon the selections in another item.

  • Content -- pluggable content types used as panes in Panels and other modules like Dashboard.


Content Construction Kit (CCK)


The Content Construction Kit allows you to add custom fields to nodes using a web browser.

Administration menu


Provides a theme-independent administration interface (aka. navigation, back-end). It's a helper for novice users coming from other CMS, a time-saver for site administrators, and useful for developers and site builders.

Administrative links are displayed in a CSS/JS-based menu at the top on all pages of your site. It not only contains regular menu items — tasks and actions are also included, enabling fast access to any administrative resource your Drupal site provides.

Wysiwyg


Allows to use client-side editors to edit content. It simplifies the installation and integration of the editor of your choice. This module replaces all other editor integration modules. No other Drupal module is required.

Wysiwyg module is capable to support any kind of client-side editor. It can be a HTML-editor (a.k.a. WYSIWYG), a pseudo-editor (buttons to insert markup into a textarea), or even Flash-based applications. The editor library needs to be downloaded separately. Various editors are supported (see below).

Wysiwyg module also provides an abstraction layer for other Drupal modules to integrate with any editor. This means that other Drupal modules can expose content-editing functionality, regardless of which editor you have installed.

Date


This package contains both a flexible date/time field type Date field and a Date API that other modules can use.

IMCE


IMCE is an image/file uploader and browser that supports personal directories and quota.

Google Analytics


Adds the Google Analytics web statistics tracking system to your website.

The module allows you to add the following statistics features to your site:

  • Single/multi/cross domain tracking

  • Selectively track/exclude certain users, roles and pages

  • Monitor what type of links are tracked (downloads, outgoing and mailto)

  • Monitor what files are downloaded from your pages

  • Custom variables support with tokens

  • Custom code snippets

  • Site Search support

  • AdSense support

  • Tracking of Goals

  • Anonymize visitors IP address

  • Cache the Google Analytics code on your local server for improved page loading times

  • Access denied (403) and Page not found (404) tracking

  • DoNotTrack support (non-cached content only)


Webform


Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

ImageAPI


This API is meant to be used in place of the API provided by image.inc. You probably do not need to install this module unless another module are you using requires it. It provides no new features to your Drupal site. It only provides an API other modules can leverage. Currently GD2 and ImageMagick support are distributed with ImageAPI.

Note: Requires PHP5!

Backup and Migrate


Backup and Migrate simplifies the task of backing up and restoring your Drupal database or copying your database from one Drupal site to another. It supports gzip, bzip and zip compression as well as automatic scheduled backups.

With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server, and to restore from an uploaded or previously saved database dump. You can chose which tables and what data to backup and cache data is excluded by default.

Link


The link module can be count to the top 50 modules in Drupal installations and provides a standard custom content field for links. With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

Advanced help


The advanced help module allows module developers to store their help outside the module system, in pure .html files. The files can be easily translated simply by copying them into the right translations directory. The entire system can appear in a popup or not as the module prefers (and by taking away access to view the popups, a site can force the popups to not exist).

The system ties into Drupal's search system and is fully indexed, so the entire contents can be searched for keywords. the help files can be placed in a hierarchy as well, allowing for top down navigation of the help.

By itself, this module doesn't do much; it requires another module to support it, but it does come with a nice little sample of text from Wikipedia to demonstrate the system.

Accessing Advanced_help


When this module is installed, users with the view advanced help index permission can access the advanced help index by going to Administer -> Advanced Help (http://www.example.com/admin/advanced_help). Additional view advanced help popup and view advanced help topic permissions enable them to access the actual help pages and popups.

Libraries API


The common denominator for all Drupal modules/profiles/themes that integrate with external libraries.

This module introduces a common repository for libraries in sites/all/libraries resp. sites/<domain>/libraries for contributed modules.

External libraries
Denotes libraries ("plugins") that are neither shipped nor packaged with a project on drupal.org. We do not want to host third-party libraries on drupal.org for a multitude of reasons, starting with licensing, proceeding to different release cycles, and not necessarily ending with fatal errors due to conflicts of having the same library installed in multiple versions.
Drupal 7 only has built-in support for non-external libraries via hook_library(). But it is only suitable for drupal.org projects that bundle their own library; i.e., the module author is the creator and vendor of the library. Libraries API should be used for externally developed and distributed libraries. A simple example would be a third-party jQuery plugin.

CAPTCHA


A CAPTCHA is a challenge-response test most often placed within web forms to determine whether the user is human. The purpose of CAPTCHA is to block form submissions by spambots, which are automated scripts that post spam content everywhere they can. The CAPTCHA module provides this feature to virtually any user facing web form on a Drupal site.

XML sitemap


The XML sitemap module creates a sitemap that conforms to the sitemaps.org specification. This helps search engines to more intelligently crawl a website and keep their results up to date. The sitemap created by the module can be automatically submitted to Ask, Google, Bing (formerly Windows Live Search), and Yahoo! search engines. The module also comes with several submodules that can add sitemap links for content, menu items, taxonomy terms, and user profiles.

CKEditor - WYSIWYG HTML editor


CKEditor is the next version of FCKeditor. The editor has been rebranded and completely rewritten. It is now much faster (the code has been optimized), loads faster (the number of files has been reduced, so the browser will perform less HTTP requests) and developers friendly.

jQuery UI


A wrapper module around the jQuery UI effects library that lets module developers add swooshy, swishy effects to their code.

jQuery Update


Upgrades the version of jQuery in Drupal core to a newer version of jQuery.

Panels


The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Poormanscron


A module which runs the Drupal cron operation using normal browser/page requests instead of having to set up a crontab to request the cron.php script. The module inserts a small amount of JavaScript on each page of your site that when a certain amount of time has passed since the last cron run, calls an AJAX request to run the cron tasks. Your users should not notice any kind of delay or disruption when viewing your site. However, this approach requires that your site gets regular traffic/visitors in order to trigger the cron request.

Lightbox2


The Lightbox2 module is a simple, unobtrusive script used to overlay images on the current page. It's a snap to setup and works on most modern browsers.

Views Slideshow


Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

Potential uses



  • News item slideshow (such as the title, image and teaser of the last 5 news articles submitted)

  • The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).

  • Rotate any image, based on any filters you can apply in views.

  • Hottest new products for any ecommerce drupal site.

  • Rotate contact links, share links, etc.

  • Heck, you could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.

  • Its also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.


The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.

Oct 7, 2011

Must have modules for creating a site in Drupal 7.x

Ctools

This suite is primarily a set of APIs and tools to improve the developer experience. It also contains a module called the Page Manager whose job is to manage pages. In particular it manages panel pages, but as it grows it will be able to manage far more than just Panels.

Custom Breadcrumbs

Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.

No new features are planned for these versions, but they are still supported and bug reports are encouraged.

Fivestar

The Fivestar voting module adds a clean, attractive voting widget to nodes in Drupal 5, node and comments in Drupal 6, and any entity in Drupal 7

Panels

The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Pathauto

The Pathauto module automatically generates path aliases for various kinds of content (nodes, categories, users) without requiring the user to manually specify the path alias. This allows you to get aliases like /category/my-node-title.html instead of /node/123. The aliases are based upon a "pattern" system which the administrator can control.

Porter-Stemmer

This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.

The process of stemming reduces each word in the search index to its basic root or stem (e.g. 'blogging' to 'blog') so that variations on a word ('blogs', 'blogger', 'blogging', 'blog') are considered equivalent when searching. This generally results in more relevant search results.

Rules

The rules modules allows site administrators to define conditionally executed actions based on occurring events (known as reactive or ECA rules).

Token

Tokens are small bits of text that can be placed into larger documents via simple placeholders, like %site-name or [user]. The Token module provides a central API for modules to use these tokens, and expose their own token values.

Views

The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Traditionally, Drupal has hard-coded most of this, particularly in how taxonomy and tracker lists are formatted.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content.

Webform

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.