Custom module and theme development in Drupal7


Published on

Custom module and theme development in Drupal7

Published in: Software, Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • <number>
  • Custom module and theme development in Drupal7

    1. 1. Custom Module & Theme Development in Drupal 7 By: Muhammad Arif Usman Rehman
    2. 2. Best Configuration Recommended best practice configuration: PHP5, MySQL 5.x, Apache 2.x
    3. 3. 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:
    4. 4. 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.
    5. 5. The building components of Drupal
    6. 6. Module Types  Core Modules  Contributed Modules  Custom Modules
    7. 7. 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
    8. 8. 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
    9. 9. Custom Module 1. Local to your Drupal Project 2. Not yet contributed to the contributed repository
    10. 10. 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 ....
    11. 11. 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
    12. 12. File structure
    13. 13. Module Architecture  “The building blocks of a module” Optional Optional
    14. 14. .info File  name = Event Management  description = Event Management Module.  package = Custom  version = VERSION  core = 7.x
    15. 15. .install file  function event_schema()  function event_install()  function event_uninstall()
    16. 16. .module file  Hooks  Menus  Includes
    17. 17. .inc file  Helper functions  Helper classes
    18. 18. Template(.tpl.php) files  Include view layer  HTML
    19. 19. 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. !
    20. 20. 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.
    21. 21. 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.
    22. 22. 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.
    23. 23. 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; .!system!system.api.php/function/hook_menu/7
    24. 24. hook_menu  "type": A bitmask of flags describing properties of the menu item. Many shortcut bitmasks are provided as constants in  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.
    25. 25. 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. 
    26. 26. Node api !node!node.api.php/7
    27. 27. 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. !node! node.api.php/group/node_api_hooks/7
    28. 28. 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. !node! node.api.php/group/node_api_hooks/7
    29. 29. 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. !node! node.api.php/group/node_api_hooks/7
    30. 30. 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. !topics!forms_api_reference.html/7
    31. 31. 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.
    32. 32. Form Attributes !topics!forms_api_reference.html/7
    33. 33. 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.“
    34. 34. 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.
    35. 35. $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.
    36. 36. Show form  We want to see the form!!! 1. We will add a menu link to this form. 2. Show form in a Block
    37. 37. 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.
    38. 38. Form references !  !topics!forms_api_reference.html/7
    39. 39. 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']. !system! system.api.php/function/hook_form_alter/7
    40. 40. Ajax in Form Drupal supports ajax in forms Example!ajax_example.module/7
    41. 41. Working with Javascript 
    42. 42. Database API  The Drupal 7 Database API provides a standard, vendor-agnostic abstraction layer for accessing database servers.
    43. 43. 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. }
    44. 44. Db_select() !database!
    45. 45. 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); }!database!
    46. 46. Web Services  Create a Menu  Menu “delivery_callback” should be => ‘ajax_deliver’  Write drupal_exit() at end of menu function  Flush cache
    47. 47. 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.
    48. 48. Theming  Register theme hooks  Implement theme functions  Implement default templates !system! system.api.php/function/hook_theme/7 
    49. 49. 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.
    50. 50. 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.
    51. 51. Implement theme functions  Example.
    52. 52. 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.
    53. 53. Implement default templates Example
    54. 54. 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
    55. 55. 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
    56. 56. Deployment  Challenges
    57. 57. Module Development
    58. 58. 1. Create New Module
    59. 59. 2. Create Info File
    60. 60. 3. Create Install File and Module Schema
    61. 61. 4. .module file
    62. 62. 5. Install Module
    63. 63. 6. Important Hooks
    64. 64. 7. Create New Menu
    65. 65. 8. Blocks and Forms
    66. 66. 9. Queries
    67. 67. 10. Ajaxify
    68. 68. 11. Theme and Templates