Archive for the ‘Drupal’ Category

15
Jun

Learning the operations of the different hooks available gives you the power to develop modules with drupal. In this tutorial we will be learning the operation of some basic and commonly used hooks. Inorder to operate on hooks we need to create a module which would use these hooks.

Create a directory in sites/all/modules and name it ‘mymodule’. This will be the directory of your new module and it should contain the .info and .module files.

Creating the .info file:

Before we start coding our new module, we need to create a simple text file that will hold some basic information about our module. Create a file in the ‘mymodule’ directory and call it mymodule.info. Enter the following contents into the file:

; $Id$
name = My module
description = Just a test module to learn hooks
core = 6.x

You can add more into .info files. For more information on that go here : http://drupal.org/node/231036.

Creating a .module file:

The .module file will hold all the code ie. All the hooks that the module implements goes in here. Create a ‘mymodule.module’ file in the mymodule directory. Now if you go to Administer-> Site Building -> Modules you will be able to see your new module:

Now you can enable the module. However the module will not give any results because we haven’t implemented any hooks to join in with the Drupal workflow. In the following few sections we shall look at implementing some hooks.

Hooks:

For a complete list of hooks you can go to : http://api.drupal.org/api/group/hooks/6 and also http://drupal.org/files/drupal_6_core_hooks_cheat_sheet.pdf.

We will be implementing only some of these hooks.

Hook_perm:

This hook is used to add user permissions into the permissions list. These permissions can then be selected on the user permissions page and used to restrict access to actions the module performs. Permissions are checked using user access().

Enter the following code in your .module file:

<?php
function mymodule_perm() {
return array(‘permission 1′,’permission 2′);
}

This will add permissions to the permissions list. If you would go to Administer->User Management->Permissions you will see the following:

permision

You can check if the user has a permission by using user_access() function. (eg: if(user_access(‘permission 1’) {  //do something } )

Hook_help:

The next hook is hook_help(), which allows you to create an entry in the global help page (/admin/help/) as well as providing help messages display at the top of pages. This hook accepts two parameters $path and $args. The return valu should be a string containing the help text. Here is an implementation:

function mymodule_help($path) {
switch ($path) {
case 'admin/help#mymodule':
return t('This is a module being implemented primarily for understanding hooks !');
break;
case 'node/add/story':
return t('Don\'t forget to:Enter a title, Promote to front page etc');
break;
case 'node/%/edit':
return t('Some notes on editing nodes');
break;
}}

Now if you were to go to Administer->Help, you will see a link to My Module. This will give the following page:

helppage

Also if you try to create a new story by going to node/add/story you will see the help text on the top of the page as follows:

nodestory

Similiarly if you try editing any created content you will get a help text – ‘Some notes on editing nodes’ on the top of the page. So using hook_help we created can create a help page for the module and also add help texts to top of any page in drupal using $path.

//TO BE CONTINUED

14
Jun

Hooks allow modules to interact with the Drupal core. In other words hooks allow modules to add their own stuff to Drupal’s workflow. To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and call that hook in all enabled modules that implement it.

Naming convention:

The available hooks to implement are explained here in the Hooks section of the developer documentation : http://api.drupal.org/api/group/hooks/6. Each hook has a defined set of parameters and a defined returned type. The string “hook” is used as a placeholder for the module name is the hook definitions. For example, if the module file is called example.module, then hook_help() as implemented by that module would be defined as example_help().

How hooks work? :

Drupal offers a system of callback hooks at various parts of the core code. The hooks are placed in key locations within the core code, such as when adding a user,publishing a blog etc… When the core code hits a hook, it will call out to all implementers of a given hook, finding implementers by looking for method names that adhere to the naming scheme.

For example hook_perm function is used to setup new permission types that can be granted to user account roles. If you go to the permissions page at drupal/?q=admin/user/permissions you will see a list of permissions.

permission

Drupal checks for all the modules that implements the ‘hook_perm’ In this case blog and block module implement the hook_perm as blog_perm and block_perm respectively. Similarly all implementations of hook_perm are called to generate the final list. Thus modules are adding permissions to the list by using hook_perm. Some modules like blogapi do not implement hook_perm, that’s why it is not present in the list.

So during the step by step process of executing a request Drupal executes hooks at certain points. While executing hooks Drupal finds functions in modules which implement that particular hook and executes those functions as well. Thus this way modules can intervene and add to the normal workflow of Drupal.

13
Jun

Drupal theming provides you with the ability to completely override the output that Drupal gives you by default. This tutorial will explain about making new themes to override the default theme functionality of Drupal.

Create a new directory in the sites/all/themes folder. This is the place where all user defined themes should go. Name the new directory as ‘mytheme’ which will be the name of your new theme.

Creating the .info file:

Create a .info file with the name mytheme.info. This file defines metadata for the theme, including the name of the theme, a description, its Drupal core version compatibility, and which theme engine it uses. Style sheets, JavaScripts, Block regions are also defined here. Enter the following contents now:

; $Id$
name = Mytheme
description = Just a new theme.
version = VERSION
core = 6.x
engine = phptemplate

You will notice that at the top of files you download from Drupal. org there is always a line commented out that starts with $Id:, with a name and some date information that follows after. This is a special ID tag used by the version control system used by Drupal.org (CVS) to maintain all of the core and contributed code. Your custom files don’t need this line on them but it doesn’t hurt to have it there either. The empty version of this string is simply $Id$.

Now if you go to Administer->Site Building->Themes you will be able to see your new theme in the list. Now if you select this theme you will see a disorganized output. This is the default output provided by different modules. The main page is displayed by system/page.tpl. You can see this by using the Themer info function of the Devel module.

In order to organize the page output you need to override page.tpl (theme_page()). Lets copy the page.tpl file from bluemarine theme and paste it in our theme, then empty cache (using Devel), and reload the page. Now the page is organized into different regions. If you copy the style.css file also the the page would appear styled.

Changing CSS:

Let’s start by adding a border around content items to help them stand out on the page. Using Firebug in Firefox we can find out the exact element that styles the node, which is the .node at line 232 of the styles.css. Change it as follows:

.node {
margin: .5em 0 2em; /* LTR */
border: 1px dashed #ccc;
padding: .5em;
}

Your page will now appear with dashed lines around the nodes. You can also override other CSS files, but then you will have to include it in the .info file of the theme like this example :stylesheets[all][] = system-menus.css. Simmiliarly if you are adding javascript files you need to add it to the .info file like this: scripts[] = script.js

Modifying a Template file : (*.tpl.php files)

Now let’s look at customizing the page.tpl.php file. This is the file that defines the general HTML structure of the entire page. The theme engine and enabled modules make a number of variables available to this file, and then these variables are simply output using PHP print statements. Let’s change the structure of our theme by moving the breadcrumb output up into the header region of the page.

Using the Themer info of Devel module you can find out how the breadcrumb is beign output. The parent file is page.tpl.php, so our breadcrumb is being printed from page.tpl.php. The function used to make the $breadcrumb variable is theme_breadcrumb().

breadcrumb

Open up the page.tpl.php file in your ‘mytheme’ folder and go to about line 29, where the $header variable is printed. Down at line 42 is the $breadcrumb variable we want to move.

Now let’s modify the file to output the breadcrumbs immediately after the header, by removing line 42 and restoring it as a modification to line 30 as follows:

<tr> <td colspan="2"><div><?php print $header ?><?php print $breadcrumb ?></div></td> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" id="content">

In a similiar way you can change the appearance of other items like node,block.. using node.tpl.php,block.tpl.php.

Template.php:

The last, crucial piece of Drupal theming is the ability to completely override the output that Drupal gives you by default and use your own custom markup instead. You may find that while the template files give you a lot of control, you can’t really do much about the HTML that you are given inside those variables (like $header,$breadcrumbs). You can do all the HTML editing around them that you want, but how do you crack into the variables themselves. This is where template.php comes into picture. Using template.php file we can override or add variables and also override theme functions.

Overriding/Adding Variables:

All variables that go out to a template file are first passed through a special kind of function, called a preprocess function. You can add your own preprocess function to your template.php file and get the last shot at the variables before they head out to the template. To keep things tidy, you can use one preprocess function per template; for example, you can create a mytheme_preprocess_page function to affect variables to be used in your page.tpl.php file. With this function, you can define, or redefine, any variable.

For example you can define a variable called $random_number as follows:

function mytheme_preprocess_page(&$vars) {
$vars['random_number'] = rand(1, 100);
}

Then (after clearing the Drupal cache), you can print out that variable out in your page.tpl.php file just like any other variable:

<?php print $random_number; ?>

You use the exact same procedure to override an existing variable. When you assign a variable name that is the same as the one Drupal is already using, yours will take precedence.For example to change $submitted from ‘Submitted by…’ to ‘Posted on…’ :

function mytheme_preprocess_node(&$vars) {
$vars['submitted'] = t('Posted on ') .format_date($vars['node']->created, 'custom', 'F j, Y');
}

Here is documentation listing all variables available in page.tpl.php, node.tpl.php, and block.tpl.php.

Overriding Theme functions: (theme hooks)

Much of Drupal’s HTML output is easily accessible in template files. But what about something like the page’s “breadcrumb trail,” Unfortunately, there’s no breadcrumb.tpl.php file. In this situation, you need to dig a little bit deeper, to the place where remaining markup in Drupal is initially defined: ‘theme functions’.

Theme functions are regular PHP functions located in Drupal’s code whose names begin with theme_ (present in theme.inc). Every element on the page that is not in a template file is run through a theme function, such as the theme_breadcrumb() function. The function basically just takes an array of HTML links and uses PHP’s implode() function to concatenate the values using the » character, wrapping this in a <div> with the class of “breadcrumb.”

function theme_breadcrumb($breadcrumb) { if (!empty($breadcrumb)) { return '<div>'. implode(' » ', $breadcrumb) .'</div>'; }}

In its current state, this function will print out the breadcrumb trail on a page, such as Home » Administer » Site building » Themes. But what if we decide that we’d rather the breadcrumb be printed as Home::Administer::Site building::Themes, with doublecolons instead?  The proper way to handle overriding theme functions is by simply copying the function into your template.php file and naming it according to Drupal’s naming conventions so that it’s recognized. Then you can modify it however you like.

function mytheme_breadcrumb($breadcrumb) {
if (!empty($breadcrumb)) {
return '<div>'. implode(' :: ', $breadcrumb) .'</div>';
}}

13
Jun

Drupal uses default theme files in modules for producing output. For example if you check out drupal\modules\system you can see some template files like page.tpl,box.tpl etc. All these template files, CSS, JavaScript, images, and HTML can be overridden by a Drupal theme. Modules generate the contents of a given page, and the theme system provides the opportunity to cut in and customize the page before it’s displayed.

The Theme System :

themsys

Each path in Drupal corresponds to a particular module that is responsible for handling the page request. For example, “node/1” is handled by the Node module, “admin/build/themes” is handled by the System module. Once the module has built up the contents of the page, it calls up the theme system with a special function called theme().

The theme() function:

Theme functions are never called directly. They are instead called through a function called theme(). So even though a module may define a function such as theme_username(), when the module needs to output its code, it would call theme(‘username’) instead. The theme() function is what makes this system of overrides possible. For eg: if theme_breadcrumb() function (present in includes/ themes.inc) has not been overridden then it is called else the overriding function(which would be present in template.php of theme) would be called.

What files constitute a theme ?

Themes are present in the drupal/themes directory. Drupal provides a no of themes like bluemarine, garland, chameleon etc..Some of these uses PHPtemplate engine like bluemarine, garland (*.tpl.php files) while others like chameleon dont use template engines. Using PHPTemplate engine we can create .tpl files (uses HTML and PHP) to override theme functions. For eg: to override theme_page() we can make a file called page.tpl.php. However themes that do not use the PHPtemplate engine, have to uses a .theme files which is pure php and contains overriding functions. (chameleon_page(),chameleon_node()..).

Themes also contain CSS,javascript,images which integrate with the template files to produce the desired output. Lets check out the contents of the bluemarine theme :

bluemarine

themename.info (bluemarine.info):

This file defines a variety of metadata for the theme, including the name of the theme, a description, its Drupal core version compatibility, and which theme engine it uses. Beyond those basics, the .info file can also define the block regions available to the theme, and the CSS stylesheets and JavaScript files used.

Template files (page.tpl,block.tpl..):

With these files, using Drupal’s PHPTemplate file naming convention, you are able to ‘override’ the default theme function. Each one controls the layout of certain parts of the template. To edit the display of blocks, nodes, and comments, edit the block.tpl.php, node.tpl.php and comment.tpl.php files respectively. The content generated by these files is used in page.tpl.php.

These files are overriding the default files. All you have to do is find the default template file, copy it into your theme folder, and edit it. Many themes start with these main Drupal core default templates:

  • page.tpl.php (located in modules/system): Controls the layout of the entire page. This isn’t for the page content type; you can think of it more as the overall screen in which your content types and blocks are displayed.
  • node.tpl.php (located in modules/node): This is used for the display of each individual node.
  • block.tpl.php (located in modules/system): This is used for all of the blocks on the site.
  • comment.tpl.php (located in modules/comment): Each individual comment is displayed with this file.
  • box.tpl.php (located in modules/system): For the container element that surrounds search results and that surrounds a list of comments that is attached to a node.

You can find any other templates in the folder of the module that created it. for example, forum templates will be in the forum module folder (modules/forum). For a list of these : http://drupal.org/node/190815.

Images and CSS :

Stylesheets can be used along with templates to create the desired look. The theme uses styles.css which is included by default. Also other stylesheets can be used but then you must declare it in the .info file. Images include the logo (logo.png) and the screenshot (screenshot.png).

Template.php :

This file can be seen in garland theme. This file can be used to override theme functions (those present in theme.inc). For example we can change the appearance of the breadcrumb by overriding the theme_breadcrumb() function.

12
Jun

Drupal ships with a lot of necessary modules like Blog, Forum, Taxonomy, Poll, Locale …They do most necessary tasks when building a website. But there are also some frequently used contributed modules that gives added functionality and power to Drupal. Some examples include CCK, Views, Devel etc..

Devel Module:

Devel is one of the most useful tools for Drupal Developers and Themers alike. Devel allows you to: print database queries for each rendered page, expose some handy functions for printing complex arrays in a human-readable fashion, empty cache, rebuild menus with one click, generate dummy content (nodes, users, comments) – great for theming and testing views, Theme Developer: allows you to click any rendered element; observe which function created it; offers candidate override function and displays available arguments as well as candidate template files. You can download it here : http://drupal.org/project/devel.

devel

Content Construction Kit (CCK):

As the name suggest this module is used to build custom content types. Drupal’s  gives each one of the new content types only a “Title” and “Body” field. We’ll need quite a few more fields. With CCK you can add custom field to content types. So you can create forms
containing a variety of fields—such as checkboxes, select lists, image uploads, and many others. You can download the CCK module here: http://drupal.org/project/cck.

cck

Views Module:

The Views module is the natural counterpart to CCK. Views allows you to create pages and blocks that pull data back out and display it to your visitors. For nearly any purpose of displaying content, the Views module can provide a listing of content in a variety of ways: a table, a list of full nodes or teasers, an RSS feed, a list of individual fields, and more.  The views project page on Drupal.org describes Views as: a smart query builder that, given enough information, can build the proper query, execute it, and display the results.
To sum it up, Views gives you a very usable interface to create complex MySQL queries which are used to display your content. You can download the Views module here : http://drupal.org/project/views.

FCKeditor and IMCE:

One of the biggest criticisms of Drupal, apart from the fact that it does not come with a WYSIWYG editor built in, is that it has no built-in image handling. Out of the box, Drupal’s built-in Upload module allows anyone with “upload files” permissions to attach image files to content they create. It’s then possible for them to manually insert <img> tags linking those image files into the content they’re writing. However, that’s a pretty cumbersome process for many users, especially those attaching many images to a long post, like a magazine article. FCKeditor is a WYSIWYG editor that allows people without HTML knowledge to create rich website content. IMCE is an add-on module that can work with editors such as FCKEditor to make it easy to add images to website content. To download FCKeditor : http://drupal.org/project/fckeditor. To download IMCE: http://drupal.org/project/imce.

fckeditor

11
Jun

Drupal can be regarded as “content management system” (CMS) however it is also a “content management framework” (CMF). In other words, unlike a typical CMS, it is geared more towards configurability and customization. In addition to providing sitebuilding tools, it offers ways for programmers and developers to customize Drupal using plug-in modules. It is a sort of “builder’s kit” made up of pre-designed components that can be used as it is or can be extensively reconfigured to suit your needs. Drupal’s power comes from its more abstracted approach to handling web content and functionality.

Some of the important features:

Flexible module system
Modules are plug-ins that can modify and add features to a Drupal site. For almost any functional need, chances are good that either an existing module fits the need exactly or can be combined with other modules to fit the need.

Customizable theming system
All output in Drupal is fully customizable, so you can bend the look and feel of your site to your will.

Extensible content creation
You can define new types of content (blog, event, word of the day) on the fly. Contributed modules can take this one step further and allow administrators to create custom fields within your newly created content types.

Search engine optimization
Drupal offers support for human-readable system URLs, and all of Drupal’s output is standards-compliant; both of these features make for searchengine friendly websites.

Role-based access permissions
Custom roles and  permissions allow for fine-grained control over who can access what within the system. And existing modules can take this level of access control even further down to the individual user level.

Social publishing and collaboration tools
Drupal has built-in support for tools such as group blogging, comments, forums, and customized user profiles. The addition of almost any other feature you can imagine—for instance, ratings, user groups, or moderation tools—is only a download away.

Terminology :

We will be looking into few commonly used terms in drupal:

Modules:

All of the administrative and user functionality in Drupal, from fundamental features such as ability to log in or create content to complex functions, all come from modules. In Drupal each module provides specific functionality, and works together with other modules to enhance their functionality. Some examples of modules are the Contact module, which enables a site-wide contact form, and the User module, which handles user authentication and permission checking. The “core” drupal modules are present in the drupal/modules folder while the “contributed” modules should be placed in drupal/sites/all/modules. You can enable or disable modules by going to Administer->SiteBuilding->Modules.

modul

Users:

The next building block of a Drupal website is the concept of users. The first user you create when you build a new Drupal site is special. User 1 has permission to perform any action on the Drupal site. Every additional user can be assigned to configurable roles. Each role can be given permissions to do different things on the
website: visiting specific URLs, viewing particular kinds of content, posting comments etc.. By default, Drupal comes with two predefined roles: ‘authenticated user’ and ‘anonymous user’. Anyone who creates a user account on the site is automatically assigned the ‘authenticated user’ role, and any visitors who haven’t yet created user accounts (or haven’t yet logged in) have the ‘anonymous user’ role.

permission

Nodes:

Any form of content such as blog post, pages,news items are all stored as nodes. All nodes, regardless of the type of content they store, share a handful of basic properties such as: author,creation date,title,body. In addition to nodes basic properties, all nodes can take advantage of certain builtin Drupal features, like flags that indicate whether they’re published or unpublished and settings to control how each type of node is displayed. Permissions to create and edit each type of node can also be assigned to different user roles; for example, users with the “blogger” role could create “Blog entry” nodes, but only “administrator”
or “editor” users could create “News” nodes. Drupal comes preconfigured with two types of nodes: “Page” and “Story.” You can also create your own content types.

What happens, though, if you need to store more information than “title” and “body content?” Plug-in modules can add to Drupal’s content system new kinds of nodes that offer more features. One example (which comes with Drupal) is the “Poll” module. When users create new “Poll” nodes, they create a list of poll questions rather than the usual “body” content.The idea that new modules add properties and build on top of the node system means that all content in Drupal is built on the same underlying framework. Features like searching, rating,  and comments all become plug-and-play components for any new type of node you may define, because under the hood, Drupal knows how to interface with their base elements—nodes.

Taxonomy:

Drupal maintains almost everything as a node. So How do you separate nodes into separate categories ?. That’s exactly what Taxonomy does. It’s just a technical term for a way of organizing and classifying things. It allows the administrator of a site to set up categories of topics that nodes can be associated with when they’re created.  In Drupal, these categories are called vocabularies. Each vocabulary contains specific terms (like Mountains or Automobiles or Pets) that can be used to describe content. Drupal supports three kinds of vocabularies: simple lists of terms, organized hierarchies of terms, and “free tagging” vocabularies that allow you to define new terms as you post new content.

Comments:

Comments are merely responses by a user to a piece of content, and exist only in relation to that content. Like nodes, but to a lesser extent, comments can be expanded with contributed modules to have additional features such as ratings or file upload fields. An important point to note is that comments are not stored as nodes, they are only attached to nodes.

Blocks:

Block are widgets that fit into areas such as the sidebars, footers, and headers of a Drupal site. They’re generally used to display helpful links or dynamic lists such as “Most popular content” or “Latest comments” and similar items. By going to Administer->Site Building->Blocks  you can configure blocks to show up on certain regions, or to be hidden.

blocks

Menus:

Menus hold the navigation links to various web pages on a Drupal site. Drupal comes with three default menus.
Navigation-The main system menu. In practice, this menu is the default menu for links offered by modules, including administrative tasks.
Primary links – An empty menu provided for custom navigation needs, typically displayed very prominently in the site’s design. Major sections of the site such as “Home” and “Blog” tend to be placed in the Primary links menu.
Secondary links – Another empty menu provided for custom navigation needs, but more subdued in presentation. As a general rule, more supplementary pages such as “Terms of Service” or “FAQ” are placed in the Secondary links menu.