• Like
  • Save
Custom module and theme development in Drupal7
Upcoming SlideShare
Loading in...5
×
 

Custom module and theme development in Drupal7

on

  • 115 views

Custom module and theme development in Drupal7

Custom module and theme development in Drupal7

Statistics

Views

Total Views
115
Views on SlideShare
115
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • &lt;number&gt; <br />

Custom module and theme development in Drupal7 Custom module and theme development in Drupal7 Presentation Transcript

  • Custom Module & Theme Development in Drupal 7 By: Muhammad Arif Usman Rehman
  • Best Configuration Recommended best practice configuration: PHP5, MySQL 5.x, Apache 2.x
  • Best Configuration Web server: Apache is recommended. PHP: Drupal requires PHP 4 (4.3.5 or greater) or PHP 5. Drupal core can work with PHP4 but most of contributed modules requires PHP5. Databases: can be either MySQL or PostgreSQL.The Apache web server and MySQL database are recommended.  Other web server and database combinations: such as IIS and PostgreSQL have been tested to a lesser extent.  More information can be found at: http://drupal.org/requirements
  • Popular Issues Memory limit: Drupal consumes more memory than other sources.Therefore, you need have to increase memory limit for Drupal. Clean URL: To use "Clean URLs" feature on an Apache web server, you will need the mod_rewrite module and the access permission to local .htaccess files. PHP: In rare cases, your hosting provides PHP4. Although Drupal can still runs with PHP 4.3.5, but many contributed modules will not work properly with PHP4. So you should ensure your PHP version is 5 and above.
  • The building components of Drupal
  • Module Types  Core Modules  Contributed Modules  Custom Modules
  • Core Modules  Ships with a Standard Drupal Release  There are Core Optional and Core Required modules For example: Node => /admin/structure/types User => /admin/config/people Block => /admin/structure/block System => /admin/config/system Filter => /admin/config/content/formats Menu => /admin/structure/menu
  • Contributed Modules Over 14,297 free community- contributed modules, known as contributed modules, are available to 1. Alter and extend Drupal's core capabilities 2. Add new features 3. Customize site's behavior and appearance
  • Custom Module 1. Local to your Drupal Project 2. Not yet contributed to the contributed repository
  • Custom Module(When to write) You need to answer few questions before writing a Custom Module 1. What do you want to achieve by this custom module? 2. Did you search the Contrib Repository to see if a module is already available for that feature? 3. Have you enabled all possible Configurations of the Core & Contrib module to check if they offer you the feature you require? .If your answer is,“Yes, I have done enough research and am sure I have to write the code now”, then go ahead ....
  • Custom Module(Why to write) I have 2 reasons to write a Custom module 1. I need a new feature which is not yet available in Drupal, and probably can be contributed as a Contrib Module. 2. I don't want to keep adding additional modules to my site for small tweaks, which I can manage in only one custom module for my website. Don't be too much dependent on Contribs. 3. Performance. – Good modules are abstract – Abstraction can be slow – Slow is bad – Custom tailored code can be faster
  • File structure
  • Module Architecture  “The building blocks of a module” Optional Optional
  • .info File  name = Event Management  description = Event Management Module.  package = Custom  version = VERSION  core = 7.x
  • .install file  function event_schema()  function event_install()  function event_uninstall()
  • .module file  Hooks  Menus  Includes
  • .inc file  Helper functions  Helper classes
  • Template(.tpl.php) files  Include view layer  HTML
  • hooks  Allow modules to interact with the Drupal core.  Drupal's module system is based on the concept of "hooks".  A hook is a PHP function that is named foo_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook.  Each hook has a defined set of parameters and a specified result type.  https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7
  • hook_boot  Perform setup tasks for all page requests.  This hook is run at the beginning of the page request.  It is typically used to set up global parameters that are needed later in the request.
  • hook_init  Perform setup tasks for non-cached page requests.  This hook is run at the beginning of the page request.  It is typically used to set up global parameters that are needed later in the request. When this hook is called, the theme and all modules are already loaded in memory.  This hook is not run on cached pages.
  • hook_menu  Define menu items and page callbacks.  This hook enables modules to register paths in order to define how URL requests are handled.  Paths may be registered for URL handling only, or they can register a link to be placed in a menu (usually the Navigation menu).  A path and its associated information is commonly called a "menu router item". This hook is rarely called (for example, when modules are enabled), and its results are cached in the database.
  • hook_menu  Each menu item has a key corresponding to the Drupal path being registered.  The corresponding array value is an associative array that may contain the following key-value pairs. 1. "title": Required.The untranslated title of the menu item. 2. "description":The untranslated description of the menu item. 3. "page callback":The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead. 4. "delivery callback":The function to call to package the result of the page callback function and send it to the browser. 5. "file": A file that will be included before the page callback is called; .https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7
  • hook_menu  "type": A bitmask of flags describing properties of the menu item. Many shortcut bitmasks are provided as constants in menu.inc:  MENU_NORMAL_ITEM: Normal menu items show up in the menu tree and can be moved/hidden by the administrator. Use this for most menu items. It is the default value if no menu item type is specified.  MENU_CALLBACK: Callbacks simply register a path so that the correct function is fired when the url/path is accessed.
  • Node  All content on a Drupal website is stored and treated as "nodes".  A node is any posting, such as a page, poll, article, forum topic, or blog entry.  Comments are not stored as nodes but are always tied to one.  Treating all content as nodes allows the flexibility of creating new types of content.  It also allows you to painlessly apply new features or changes to all content.  https://drupal.org/documentation/modules/node
  • Node api  https://api.drupal.org/api/drupal/modules!node!node.api.php/7
  • Hook_node_insert  Respond to creation of a new node.  This hook is invoked from node_save() after the database query that will insert the node into the node table is scheduled for execution, after the type-specific hook_insert() is invoked, and after field_attach_insert() is called.  https://api.drupal.org/api/drupal/modules!node! node.api.php/group/node_api_hooks/7
  • Hook_node_update  Respond to updates to a node.  This hook is invoked from node_save() after the database query that will update node in the node table is scheduled for execution, after the type-specific hook_update() is invoked, and after field_attach_update() is called.  https://api.drupal.org/api/drupal/modules!node! node.api.php/group/node_api_hooks/7
  • Hook_node_delete  Respond to node deletion.  This hook is invoked from node_delete_multiple() after the type-specific hook_delete() has been invoked, but before hook_entity_delete and field_attach_delete() are called, and before the node is removed from the node table in the database.  https://api.drupal.org/api/drupal/modules!node! node.api.php/group/node_api_hooks/7
  • Form APi  Functions to enable the processing and display of HTML forms.  Drupal uses these functions to achieve consistency in its form processing and presentation, while simplifying code and reducing the amount of HTML that must be explicitly generated by modules.  https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7
  • Create Form  The process for creating a form is mainly two steps. 1. The first is to build an associative array $form that contains all the fields. 2. The second step is to return that $form variable.
  • Form Attributes  https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7
  • Create Form  It is important to note that the function takes the inputs $form, and a reference &$form_state.  This function will be called when Drupal tries to build the form "form_example_form.“
  • Validate and submit form  Now that we have a form, we need to add two more function: 1. form_example_form_validate, and 2. form_example_form_submit. .These two functions are hook functions that will be called when Drupal validates the form and when it submits the form (assuming it validated). .These two functions need to named similar to the other form, but with "validate" and "submit" at the end.
  • $form and $form_State  You will note that these three functions take the same variables. 1. $form is the original form information and can be seen as the original structure of the form. 2. $form_state holds all of the submitted values as well as other information, some of which you can add yourself.
  • Show form  We want to see the form!!! 1. We will add a menu link to this form. 2. Show form in a Block
  • What to do when your form is submitted?  From this point, you will want to either 1. save the form data, 2. send an email, or 3. display some information.
  • Form references  https://api.drupal.org/api/drupal/includes!form.inc/group/form_api/7  https://drupal.org/node/1419390  https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7
  • Alter Form  Perform alterations before a form is rendered.  One popular use of this hook is to add form elements to the node form.  When altering a node form, the node object can be accessed at $form['#node'].  https://api.drupal.org/api/drupal/modules!system! system.api.php/function/hook_form_alter/7
  • Ajax in Form Drupal supports ajax in forms Example https://api.drupal.org/api/examples/ajax_example!ajax_example.module/7
  • Working with Javascript  https://drupal.org/node/121997
  • Database API  The Drupal 7 Database API provides a standard, vendor-agnostic abstraction layer for accessing database servers.
  • Database abstraction layer  Allow the use of different database servers using the same code base.  Most Drupal database SELECT queries are performed by a call to db_query() or db_query_range()  For example, one might wish to return a list of the most recent 10 nodes authored by a given user. Instead of directly issuing the SQL query SELECT n.nid, n.title, n.created FROM noden WHERE n.uid = $uid LIMIT 0, 10; one would instead call the Drupal functions: $result = db_query_range('SELECT n.nid, n.title, n.created FROM {node} n WHERE n.uid = :uid', 0, 10, array(':uid' => $uid)); foreach ($result as$record) { // Perform operationson $record->title, etc. here. }
  • Db_select()  https://api.drupal.org/api/drupal/includes!database! database.inc/function/db_select/7
  • Transactions function my_transaction_function() { // Thetransaction openshere. $txn = db_transaction(); try { // Your codehere. } catch (Exception $e) { // Something went wrong somewhere, so roll back now. $txn->rollback(); // Log theexception to watchdog. watchdog_exception('type', $e); } https://api.drupal.org/api/drupal/includes!database!database.inc/group/database/7
  • Web Services  Create a Menu  Menu “delivery_callback” should be => ‘ajax_deliver’  Write drupal_exit() at end of menu function  Flush cache
  • Theming in drupal  The first step is that logic must be separated as much as possible from presentation.  To accomplish this, modules do as much of the work on the data as possible, and hand that data off to the presentation layer.  This is handled through the theme() function.
  • Theming  Register theme hooks  Implement theme functions  Implement default templates  https://api.drupal.org/api/drupal/modules!system! system.api.php/function/hook_theme/7  https://drupal.org/node/933976
  • Theme Hook  Register a module (or theme's) theme implementations.  Every chunk of output that is themed through the theme() function is called a theme hook.  In order to utilize a theme hook, your module first has to register that this exists.
  • Implement theme functions Drupal allows you to use functions for your default theme implementations. This is somewhat faster performance than loading template files. New in Drupal 7, theme functions can have preprocess functions just like templates. Copying and modifying template files is still considered more friendly for themers. Theme functions are named by prepending 'theme_' to the name of the hook. The arguments given to theme('hook') will be passed straight through, unaltered.
  • Implement theme functions  Example.
  • Implement default templates  When implemented as a template, the .tpl.php file is required.  It should be in the same directory as the .module file (though the 'path' directive can be used to place these templates in another directory or a sub-directory).  Templates should be as much pure HTML as possible, but there are a few functions that are explicitly encouraged in your templates: 1. t(): modules should always provide proper translatability, and templates are no exception. 2. format_date(): since this function is, really, a presentation function, the presentation layer is the appropriate place for it.
  • Implement default templates Example
  • Performance: Reduce # of HTTP Requests Problem:  80% of the end-user response time is spent on the front-end.  Most of this time is tied up in downloading all the components (images, style- sheets, scripts, Flash) in the page.  Reducing the number of components in turn reduces the number of HTTP requests required to render the page.This is the key to faster pages. Solution:  Turn on Bandwidth optimizations for CSS and JavaScript files Manual CSS sprite generator  Go for Bootstrap  Use Yslow firefox plugin
  • Performance: Cache Caching using Boost  Extension of Performance module  Instead of caching results in tables, stores them in files bypassing PHP and MySQL  Limited to anonymous visitors – Not for sites with high number of authenticated visitors How it works:  Uses apache mod_rewrite directives in .htacess to check if GET  Logged in cookie does not exist  HTML file cached on file-system
  • Deployment  Challenges
  • Module Development
  • 1. Create New Module
  • 2. Create Info File
  • 3. Create Install File and Module Schema
  • 4. .module file
  • 5. Install Module
  • 6. Important Hooks
  • 7. Create New Menu
  • 8. Blocks and Forms
  • 9. Queries
  • 10. Ajaxify
  • 11. Theme and Templates