SlideShare ist ein Scribd-Unternehmen logo
1 von 86
Downloaden Sie, um offline zu lesen
Drupal Module Development
       “Hands-on”
             Anil Sagar
          Gaurav Kumar
       Blisstering Solutions
Table Of Contents

1. Drupal Architecture …………………………………………………….03
2. Database Architecture ……………………………………………….11
3. Module Types …………………………………………………………….14
4. Hands on Module “TweetScope” ……………………………….21
5. Module Architecture ………………………………………………….26
6. Introduction of hooks ………………………………………………..33
7. hook_menu ………………………………………………………………..37
8. Form API …………………………………………………………………….43
9. Permissions and Access Control ………………………………..51
10. Schema API ………………………………………………………………56
11. Modify an existing form …………………………………………..62
12. hook_nodeapi ………………………………………………………….65
13. hook_block ………………………………………………………………70
14. Look & Feel ………………………………………………………………75
15. Bonus Topics: Eclipse, Xdebug, Coder, Firebug ………..80
16. Question and Answers ……………………………………………..85
1. Drupal Architecture
  Technology Stack L(/W)AMP
    Code Base (Drupal 6.16)
          Database




                              3
Technology Stack

Language
                    Database Abstraction Layer


 Database


Web Server



Operating
System



                                                 4
System Requirements
Web Server:
• Apache: Drupal will work on Apache 1.3 or Apache 2.x hosted
  on UNIX/Linux, OS X or Windows.
• Microsoft IIS: Drupal core will work using IIS 5, IIS 6, or IIS 7.

Database:
• MySQL: Drupal 6 supports MySQL 4.1 or higher. Recommended
   by drupal.org
• PostgreSQL: Drupal supports 7.4 or higher.

PHP:
• Recommended: PHP 5.2.x


                                                                       5
File Structure




                   all




                 default


                           6
•   includes folder: Contains libraries of common function that
    Drupal does.

•   modules folder: Contains the core modules, with each module
    in its own folder.

•   profiles folder: Contains different installation profiles for a site.
    If there are other profiles besides the default profile in this
    subdirectory, Drupal will ask you which profile you want to
    install when first installing your Drupal site.

•   scripts folder: Contains scripts for checking syntax, cleaning up
    code, running Drupal from the command line, and handling
    special cases with cron.
                                                                            7
•    sites folder:
i.    Contains the user modifications to Drupal in the form of
      settings, modules, and themes. When you add modules to
      Drupal from the contributed modules repository or by writing
      your own, they go into sites/all/modules.
ii. This keeps all your Drupal modifications within a single folder.
      Inside the sites directory there will be a subdirectory named
      default that holds the default configuration file for your Drupal
      site—default.settings.php.
iii. The Drupal installer will modify these original settings based on
      the information you provide and write a settings.php file for
      your site. The default directory is typically copied and renamed
      to the URL of your site by the person deploying the site, so your
      final settings file would be at
      sites/www.example.com/settings.php.
                                                                          8
•   themes folder: The themes folder contains the template
    engines and default themes for Drupal. Additional themes you
    download or create should not go here; they go into
    sites/all/themes.

•   cron.php file: cron.php is used for executing periodic tasks, such
    as pruning database tables and calculating statistics.

•   index.php: main entry point.

•   install.php: main entry point for the Drupal installer.

•   update.php: Updates the database schema after a Drupal
    version upgrade.

                                                                         9
•   xmlrpc.php: Receives XML-RPC requests and may be safely
    deleted from deployments that do not intend to receive XML-
    RPC requests.

•   robots.txt: Default implementation of the robot exclusion
    standard.




                                                                  10
2. Database Architecture


   Configuration   Content
     Changes       Changes




                             11
Database Architecture
For example some of the tables which stores configuration
related information are as follows:
• blocks:
         Block. This stores information about blocks provided by
             every module installed, including custom blocks.

•   blocks role:
        Block. Stores the roles permitted to view blocks in the
            system.

•   menu:
       Menu. Storage of menu module customizations.

•   system:
        System. Information about installed modules.
                                                                   12
Database Architecture
Some tables which holds content information

•   node
        Node. The main table for storing general node information,
    including the title, node number, dates, workflow state, but it does
    not store most of the actual content.

•   node_revisions
       Node. Stores information about node revisions, including the
    main content of the node.

•   users
        User. User records.

                                                                       13
3. Module Types

   Core Modules
Contributed Modules
  Custom Modules




                      14
Module Types
Drupal modules are basically categorized into three types
1. Core Modules:

        Drupal comes with 31 core modules, which address
everything from basic functions such as user management (the
User module), logging (the Watchdog module), and analysis of
access to the site (the Statistics module) to advanced features such
as managing a hierarchical series of collaborative pages that can be
versioned and moderated (the Book module). Becoming familiar
with these modules and mastering their usage will help you get the
most out of Drupal and create powerful web sites.


                                                                       15
Required Core Modules
•   Block:
         Restricted to web administrator access only.
•   Filter:
         Authorized users and web administrators can choose from
    either Filtered or Full HTML Input formats.
•   Node:
         Responsible for content.
•   System:
         Responsible for cron and caching.
         Primary Web Site Admin. only.
•   User:
         User Management, Roles, Permissions.
         Web administrator access only.

                                                                   16
Optional Core Modules
Drupal core comes with optional modules that can be
enabled if required.
• Aggregator: publishing syndicated content
• Blog: a blog for every user
• BlogApi: post from blog tools
• Book: structured document publishing
• Color: Allows the user to change the color scheme of certain
    themes
• Comment: allow comments on content
• Contact: a way for users to get in touch
• Content translation: translating posts to different languages
• Locale: multi-language support
• Menu: customize site navigation
• Open ID
• Path: readable URLs                                             17
2. Contributed Modules:

•   Although core modules can provide the basics for your site,
    and can in some cases get you pretty far, the real power in
    Drupal comes from its vast array of community-contributed
    modules.

•   You can browse and download all contributed modules from
    http://drupal.org/project/Modules

•   Once you’ve downloaded and extracted the module directory,
    place it into the sites/all/modules/contrib directory and your
    new module should appear on the Module administration
    page www.yoursite.com/admin/build/modules.


                                                                     18
Some Widely Used Contributed Modules:
•   Views
         This tool is essentially a smart query builder that, given
enough information, can build the proper query, execute it, and
display the results.

•   Content Construction Kit (CCK)
       Most content in a Drupal site will come from instances of
Content Types. The Content Construction Kit allows you to add
custom fields to any of the content types using a web interface.

•   Google Analytics
        Adds the Google Analytics web statistics tracking system
to your website.
                                                                      19
3. Custom Modules

•   To extend functionality of contributed modules.

•   To build features that are specific to your site.

•    To build features that are not available through core or
    contributed modules.




                                                                20
4. Hands On Module
                 “TweetScope”
What is tweetscope ?

•   Display node related tweets in your node display page.

Why a custom module ?

•   No existing contributed module has this feature out of the box.




                                                                      21
Lets Build A Module
               “TweetScope Module”

  Specify
                                 Display Twitter
 keywords         Find Results                     Theme the
                                 Results in node
related to a      From Twitter                       results
                                      page
   node




                                                               22
TweetScope Module Requirements

•   Administrator can configure which are all node types he want to
    display related tweets, using simple form.

•   Database to store keywords and node id for fetching twitter
    results.

•   Altering the node add form to create a simple text field which
    captures keyword related to particular node.

•   A simple block which displays related tweets of a node.



                                                                      23
Tasks
In our module we are going to accomplish the following tasks:

1. Creating a simple administrator settings page using hook_menu.
2. A simple form using hook_form in the above page to store
   tweetscope admin settings.
3. How to validate form using validate and submit functions.
4. How to display notification messages and errors using
   drupal_set_message.
5. How to define permissions to restrict access to the administrator
   page that we created in step 1.
6. How to create a simple schema for storing keywords related to a
   node using hook_schema in .install file and hook_install and
   hook_uninstall functions to install and uninstall schema.

                                                                       24
Tasks (Continued)
7. How to alter existing node add form using form_alter to add
    additional field which captures keyword related to a particular
    node.
8. How to update the keywords for a particular node using
    hook_nodeapi
9. How to create a simple block using hook_block to display
    twitter results.
10. How to theme a block using hook_theme.




                                                                      25
5. Module Architecture
“The building blocks of a module”

                                      The .module
 The .info file   The .install file
                                           file




                                                    26
Module Architecture
1.    In Drupal, every module is contained in its own directory. This
     simplifies organization; all of the module's files are located in
     one place.
2.    To keep naming consistent throughout the module (a standard
     in Drupal), we will name our directory with the module name.
3.   Basic files that are required for every module are :
4.   .info file
5.   .module file
6.   Some optional files depending on type of functionality module
     required are:
7.   .install file                           .js file
8.   .inc file (Include file)                .css file


                                                                         27
.info file
•   Drupal uses .info files (aka, "dot info files") to store metadata
    about themes and modules. Various Drupal components use the
    information in this file for module management.


•   The .info file should have the same name as the .module file
    and reside in the same directory. For example, if our module is
    named tweetscope.module then your .info file should be
    named tweetscope.info.




                                                                        28
tweetscope.info File
; $Id$
name = “Tweetscope”
description = “Provides tweets related to a node.”
core = 6.x
;$id$ The first line of the file is, at first glance, the
most cryptic. However, its function is mundane: it is a placeholder for
Drupal's
CVS server.

name (Required) The displayed name of your module. It should follow
the Drupal capitalization standard: only the first letter of the first word is
capitalized ("Example module"). Spaces are allowed as the name is used
mainly for the display purposes.

name = “Tweetscope"                                                       29
tweetscope.info File
description (Required) A short, preferably one line description that
will tell the administrator what this module does on the module
administration page. Remember, overly long descriptions can make
this page difficult to work with, so please try to be concise. This field
is limited to 255 characters.

description = "Provides tweets related to a node.“

core (Required) The version of Drupal that your module is for. For
Drupal 6 this would be 6.x, Drupal 7 would be 7.x, etc. Note that
modules cannot specify the specific version of a branch of Drupal. 6.x
is correct 6.2 is not.

core = 6.x
                                                                            30
tweetscope.info File
.info module meta data is used to display module related information
in modules list page




                                                                       31
tweetscope.module File

•   The purpose of a module is to extend Drupal's
    capabilities.

•   A module is a bundle of PHP code and supporting files
    that use Drupal's APIs and architecture to integrate new
    functional components into the Drupal framework.

How Does Drupal Communicate with the module ?

    This is done through hook mechanism in Drupal
    •




                                                               32
6. Introduction to Hooks
     What are hooks?
     Why should I care?




                           33
What are hooks?
•   A hook is really nothing more than a function that matches the
    pattern of a call to the module functions .

•   You can say that hook is a simple callback function that is called
    on specific events.

•   Pattern modulename_hookname()

•   For example, if you want to do some operation on user login,
    say sending an email to administrator on user logins into the
    site, then no need to change the code in user module.

•   Implement hook_user on your own module say “alert” by
    defining function in your module file called alert_user and write
    code to send an email to administrator here.
                                                                         34
Why should I care?
•   Modules Extends it’s functionality through hook system.

•   One module communicates through other module through
    hooks.

•   The Hooks API provides a common naming standard for hooks,
    allowing developers to implement them in custom modules
    without needing to engage in extensive programming.

•   The Hooks API allows developers to create their own hooks that
    other modules can access, that leverage the same techniques
    used in core Drupal.

•   Many hooks are state aware, and operate differently depending
    on what Drupal is actually doing when the hook is triggered.
                                                                     35
Our First Coding Task
1. Creating a simple administrator settings page using hook_menu.

•   Path of our administration page is
    admin/settings/tweetscope

•   Title of the pages is Tweetscope administrator settings.

•   This page should display settings form to configure the
    nodes that can able to display tweets related to that node.

•   We need to restrict access to this page only for specific roles
    of users by creating permissions.


                                                                      36
7. hook_menu
“The drupal page request
        handler”




                           37
hook_menu
•   hook_menu defines menu items and page callbacks.

•   This hook enables modules to register paths, which
    determines whose requests are to be handled. Depending on
    the type of registration requested by each path, a link is
    placed in the the navigation block and/or an item appears in
    the menu administration page.

•   You can check more about this hook at
    http://api.drupal.org/api/function/hook_menu




                                                                   38
tweetscope_menu()
function tweetscope_menu() {
  $items = array();
  $items['admin/settings/tweetscope'] = array(
    'title' => 'Tweetscope Settings',
    'description' => 'Contains settings for my module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('tweetscope_form'),
    'access callback' => 'user_access',
    'access arguments' => array('administer tweetscope')
  );
  return $items;
}

                                                           39
tweetscope_menu()
•   The first line of function is function declaration, which follows
    pattern modulename_hookname.

•    hook_menu returns an array of menu items. Each menu item
    has a key corresponding to the Drupal path being registered. The
    item is an associative array that may contain different key-value
    pairs.

•   The second line defines $items array. In the next line we defined
    a new item by defining path “admin/settings/tweetscope” as key
    of the array.

•   We defined other parameters as key – value pairs in an associate
    array.
                                                                        40
tweetscope_menu()
•   "access callback": A function returning a boolean value that
    determines whether the user has access rights to this menu
    item. Defaults to user_access() unless a value is inherited
    from a parent menu item.

•   "access arguments": An array of arguments to pass to the
    access callback function.




                                                                   41
Time To Extend
•   A simple form using hook_form in the above page to store
    tweetscope admin settings.
•   How to validate form using validate and submit functions.
•   How to display notification messages and errors using
    drupal_set_message.
     •    Display all node types as checkboxes to select node types
         that will have related tweets.

    •    Validate form such that at least one node type is enabled
         for displaying related tweets.

    •    Set notification messages on failure of above validation.

    •    On successful validation save the results and display
         successful notification using drupal_set_message.            42
8. The FORM API
      hook_form
  Form API elements
    Form Validate
     Form Submit
 drupal_set_message
   drupal_set_error


                      43
tweetscope_form()
function tweetscope_form() {
  $form = array();
  $form['settings'] = array(
    '#type' => 'fieldset',
    '#title' => 'TweetScope Settings'
  );
  $form['settings']['node-types'] = array(
    '#type' => 'checkboxes',
    '#options' => node_get_types('names'),
    '#title' => 'Node Types',
    '#description' => 'Tweetscope will be available for the follwing content types',
    '#default_value' => variable_get('tweetscope_node_types', array())
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );
  return $form;
}
                                                                                       44
tweetscope_form()
•    tweetscope_form function is called through menu page
    callback function drupal_get_form which takes argument
    form_id as tweetscope_form

•   Return value is an array containing the form elements to be
    displayed in the form.




                                                                  45
tweetscope_form()
We defined three form elements in our form function.
• First element fieldset specifes For form groups, the '#type'
   parameter is set to 'fieldset', and notice how the ‘settings'
   form group is made into a collapsed form group with the
   addition of a few attributes.

•   Second element gives all node types selectable as checkboxes,
    the '#type' parameter is set to ‘checkboxes', and options are
    populated using node_get_types function which returns an
    array of node type names.

•   Last one is submit form element, the '#type' parameter is set
    to ‘submit', and the label is set to “Submit” using #value
    parameter.
                                                                    46
tweetscope_form_validate
function tweetscope_form_validate($form, &$form_state) {
  $flag = 0;
  foreach($form_state['values']['node-types'] as $key => $value) {
    if($key === $value) {
            $flag = 1;
          }
  }
  if($flag == 0) {
    form_set_error('settings','Select atleast one value');
  }
}



                                                                     47
tweetscope_form_validate
•    Accepts $form_state a keyed array containing the current
    state of the form as parameter. The current user-submitted
    data is stored in $form_state['values'], though form
    validation functions are passed an explicit copy of the values
    for the sake of simplicity.

•    We check for at least one node type is selected, by
    comparing key - value pairs.

•   If none of the node types are selected then we set an error
    message using form_set_error function.

•   If validation passes successfully, control is passed to
    tweetscope_form_submit function.
                                                                     48
tweetscope_form_submit

function tweetscope_form_submit($form, &$form_state) {
  variable_set('tweetscope_node_types', $form_state['values']['node-
types']);
  drupal_set_message('Your form has been submitted');
}




                                                                       49
tweetscope_form_submit
•    Accepts $form_state a keyed array containing the current
    state of the form as parameter.

•    We save the settings in a variable using variable_set
    function which takes variable name as first argument and
    value as second argument.

•   Variable value can be retrieved using variable_get function.

•   After storing the result successfully we display the
    notification message using drupal_set_message function
    which takes message as an argument.


                                                                   50
9. Permissions, Access Control
“The safe way is the only way”




                                 51
Permissions, Access Control
hook_perm
http://api.drupal.org/api/function/hook_perm
function tweetscope_perm() {
  return array('administer tweetscope');
}

•   Define user permissions.

•   This hook can supply permissions that the module defines, so
    that they can be selected on the user permissions page and used
    to grant or restrict access to actions the module performs.

Return value
An array of permission strings.
                                                                      52
Permissions, Access Control
Once hook_perm is defined we can see the permissions settings
at admin/user/permissions




                                                                53
.install file
•   A .install file is run the first time a module is enabled, and is used to
    run setup procedures as required by the module. The most common
    task is creating database tables and fields. The .install file does not
    have any special syntax. It is merely a PHP file with a different
    extension.

•   Implements hook_install which installs table when module is
    enabled.

•   Implements hook_uninstall which drops table when module is
    uninstalled.

•   .install files are also used to perform updates when a new version of a
    module needs it.

                                                                                54
Tweetscope Table:
Tweetscope table contains two fields. The fields are described as
below.

nid:
Primary key of the table which stores unique id of node.

Data Type: int
Length : 10

keywords:
Stores keywords related to a node.

Data Type: Varchar
Length: 255
                                                                    55
10. The Schema API
http://api.drupal.org/api/group/schemaapi/6

               hook_schema
                hook_install
               hook_uninstall


                                              56
tweetscope_schema
•   A Drupal schema definition is an array structure representing
    one or more tables and their related keys and indexes.

•   By implementing hook_schema() and specifying the tables your
    module declares, you can easily create and drop these tables on
    all supported database engines.

•   Drupal supports MySQL and PostgreSQL databases.


Return value
A schema definition structure array. For each element of the array,
the key is a table name and the value is a table structure definition.

                                                                         57
tweetscope_schema
function tweetscope_schema() {
  $schema = array();
  $schema['tweetscope_node'] = array(
    'description' => 'Stores node to keyword mapping',
    'fields' => array(
      'nid' => array(
        'type' => 'int',
        'not null' => TRUE
       ),
       'keywords' => array(
         'type' => 'varchar',
         'length' => '255',
         'default' => ''
         )
       ),
     'primary key' => array('nid')
  );
  return $schema;
                                                         58
}
hook_install()

•   The hook will be called the first time a module is installed.

•   Installs the schema that we created earlier.

•   Creates necessary tables that we defined in hook_schema.

    function tweetscope_install() {
      drupal_install_schema('tweetscope');
    }

•   drupal_install_schema($module) Create all tables that a
    module defines in its hook_schema()

                                                                    59
hook_uninstall()
•   Remove any tables or variables that the module sets.

•   The uninstall hook will fire when the module gets uninstalled.

•   Drops tables that we defined in hook_schema.

    function tweetscope_uninstall() {
      drupal_uninstall_schema('tweetscope');
    }

•   drupal_uninstall_schema($module) Drops all tables that a
    module defines in its hook_schema()


                                                                     60
Altering Node Forms
•    As per tweetscope node settings, we need to alter node add
    forms with new text field which captures keyword related to a
    node.

•   Display the keyword in node edit form if a particular node is
    already configured with a related keyword.

•   On insert or update of a node we need to insert or update
    keyword into tweetscope table that we created earlier using
    hook_schema.




                                                                    61
11.Modify an existing form

               hook_form_alter
http://api.drupal.org/api/function/hook_form_alter




                                                     62
hook_form_alter(&$form, &$form_state, $form_id)


   •   Perform alterations before a form is rendered.


Parameters

   •   $form Nested array of form elements that comprise the form.

   •   $form_state A keyed array containing the current state of the
       form.

   •   $form_id String representing the name of the form itself.


                                                                       63
tweetscope_form_alter(&$form, &$form_state, $form_id)
 function tweetscope_form_alter(&$form, &$form_state, $form_id) {
   $node_types = variable_get('tweetscope_node_types', array());
   foreach ($node_types as $key => $value) {
     if ($value !== 0) {
       if ($form_id == $key.'_node_form') {
         $form['keywords'] = array(
           '#type' => 'textfield',
           '#title' => 'TweetScope Keywords',
           '#description' => 'Specify your twitter keywords here.',
           '#default_value' => db_result(db_query("SELECT keywords FROM {tweetscope_node}
 where nid = %d", arg(1))),
           '#size' => '60',
         );
       }
     }
   }
 }
                                                                                       64
12. Node operations
     “The king of all hooks”
               hook_nodeapi
http://api.drupal.org/api/function/hook_nodeapi/6




                                                    65
hook_nodeapi
    • Act on nodes defined by other modules.
Parameters
    • &$node: The node the action is being performed on.
    • $op: What kind of action is being performed. Possible values:
    • "delete": The node is being deleted.
    • "insert": The node is being created (inserted in the database).
    • "update": The node is being updated.
    • "view": The node content is being assembled before rendering.
       The module may add elements $node->content prior to rendering.
    • $a3
       For "view", passes in the $teaser parameter from node_view().
       For "validate", passes in the $form parameter from
    node_validate().
    • $a4
       For "view", passes in the $page parameter from node_view().    66
Case “insert”
•    Find the node types that currently have tweetscope feature
    enabled.

•    Compare the node types with the node that is ready to
    submit.

•    If matches retrieve the value of keyword textfield that we
    added to node add form using hook_form_alter

•   Store the result into tweetscope table with nid and keyword.

Case “update”
•   Update the result stored in tweetscope table.

                                                                   67
tweetscope_nodeapi
function tweetscope_nodeapi(&$node, $op , $a3, $a4) {
  $node_types = variable_get('tweetscope_node_types', array());
  foreach ($node_types as $key => $value) {
    if ($value !== 0) {
      if ($node->type == $key) {
        switch ($op) {
          case 'insert':
           db_query("INSERT INTO {tweetscope_node} (nid, keywords) VALUES (%d, '%s')",
$node->nid, $node->keywords);
           break;
          case 'update':
           db_query("UPDATE {tweetscope_node} SET keywords = '%s' where nid = %d",
$node->keywords, $node->nid);
           break;
        }
      }
    }
  }
                                                                                      68
}
Time to see results !!
•    Implement hook_block to see results in a block.

•    Enable the block in node display pages.

•    Retrieve the keyword associated with a particular node from
    tweetscope table.

•    Retrieve the results from twiiter using twiiter search API
    using json format.

•    Decode the results from json to array and display the results.

•     Theme the results using hook_theme function and Cascading
    Style Sheets

                                                                      69
13. The Module’s Block

                hook_block
http://api.drupal.org/api/function/hook_block/6




                                                  70
hook_block($op = 'list', $delta = 0, $edit = array())

•   Declare a block or set of blocks.

Parameters

•   $op What kind of information to retrieve about the block
    or blocks. Possible values:
•   'list': A list of all blocks defined by the module.
•   'configure': Configuration form for the block.
•   'save': Save the configuration options.
•   'view': Process the block when enabled in a region in order
    to view its contents.



                                                                  71
hook_block($op = 'list', $delta = 0, $edit = array())

•   $delta Which block to return (not applicable if $op is 'list').
    Although it is most commonly an integer starting at 0, this is not
    mandatory. For instance, aggregator.module uses string values
    for $delta

•   $edit If $op is 'save', the submitted form data from the
    configuration form.




                                                                         72
hook_block
Case “list”
•      Returns an array of blocks which holds information of block.
function tweetscope_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
   case 'list':
    $blocks[0]['info'] = "Twitter Results";
    return $blocks;
    break;
  }
}




                                                                         73
Case “view”
 •     Returns content that will be rendered on block.
 case 'view':
    switch ($delta) {
     case 0:
      $keyword = db_result(db_query("SELECT keywords FROM {tweetscope_node}
 where nid = %d", arg(1)));
      if ($keyword != '') {
         $twitter_results =
 json_decode(file_get_contents('http://search.twitter.com/search.json?q='.$keyword));
         foreach($twitter_results->results as $tweet => $tweet_value) {
           $blocks['content'] .= theme('tweetscope_tweet', $tweet_value->text,
 $tweet_value->from_user, $tweet_value->profile_image_url);
          }
       }
       else {
         $blocks['content'] = 'No twitter results exist for this page!!';
       }
       $blocks['subject'] = 'Twitter Results';
                                                                                     74
       return $blocks;
14. Look & Feel

                hook_theme
http://api.drupal.org/api/function/hook_theme/6




                                                  75
hook_theme
•   To register a module theme function we need to implement
    hook_theme.

•    hook_theme defines new theme function called
    tweetscope_tweet which themes the output of themes.

•   hook_theme return an associative array which has theme function
    name as key and arguments as an associative array.

•    Implementation of theme function is writing a function with
    pattern theme_themefunctionname that we defined in
    hook_theme.


                                                                   76
tweetscope_theme
function tweetscope_theme() {
  return array(
    'tweetscope_tweet' => array(
       'arguments' => array('tweet' => NULL, 'tweet_user' => NULL, 'img' =>
NULL),
     ),
  );
}

•   Defines a new theme function – tweetscope_tweet

•   Accepts three parameters: tweet, tweet_user. img


                                                                        77
Implementation of
theme_tweetscope_tweet
•   Return the output wrapped inside div tags.

•   Write Cascading Style Sheets to theme the output.

•   Include Cascading Style Sheet in our module.

•   Return the themed output.




                                                        78
Implementation of
theme_tweetscope_tweet
function theme_tweetscope_tweet($tweet, $tweet_user, $img) {
  $module_path = drupal_get_path('module', 'tweetscope');
  $full_path = $module_path .'/tweetscope.css';
  drupal_add_css($full_path);
  $output = '<div id="tweet-image"><img src="'. $img
.'"></img></div><div id="tweetscope-tweet">'. $tweet .'</div><div
id="tweet-user"><strong>By </strong>'. $tweet_user .'</div>';
  return $output;
}



                                                                    79
15. Bonus Topics
     Ecplise
      Coder
     Xdebug
     Firebug



                   80
Eclplise PDT
http://download.eclipse.org/tools/pdt/downloads/


•   Editor - code completion and syntax coloring

•   Faster development, fewer coding errors

•   Editor - auto line-numbering, code collapsing

•   Debugging

•   Visual Layout - alignment, spacing, sizing options.


                                                          81
Coder
•   Indentation Check

•   Coding Standards

•   Security Guidelines

•   Warnings and Errors




                          82
Xdebug
•   Install Xdebug

•   Configure php.ini settings

•   Configure your eclipse

•   Break Points

•   Happy Debugging




                                 83
•   JavaScript Debugging and Profiling

•   "Live" editing and inspection of (X)HTML code

•   CSS editing, modification and visual highlighting.

•   HTTP Related Network Monitoring




                                                         84
Any Questions ??
                   85
Anil Sagar (anil.sagar @ blisstering.com)
Gaurav Kumar (gaurav.kumar@blisstering.com)

            Blisstering Solutions
           (www.blisstering.com)




                                              86

Weitere ähnliche Inhalte

Was ist angesagt?

10 New Things You Can Do with Drupal 8 Out-of-the-Box
10 New Things You Can Do with Drupal 8 Out-of-the-Box10 New Things You Can Do with Drupal 8 Out-of-the-Box
10 New Things You Can Do with Drupal 8 Out-of-the-BoxSuzanne Dergacheva
 
Drupal 7 Features - Introduction - Basics
Drupal 7 Features - Introduction - BasicsDrupal 7 Features - Introduction - Basics
Drupal 7 Features - Introduction - BasicsDhinakaran Mani
 
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course OverviewFrom Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course OverviewItalo Mairo
 
Speedrun: Build a Website with Panels, Media, and More in 45 Minutes
Speedrun: Build a Website with Panels, Media, and More in 45 MinutesSpeedrun: Build a Website with Panels, Media, and More in 45 Minutes
Speedrun: Build a Website with Panels, Media, and More in 45 MinutesAcquia
 
Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8Italo Mairo
 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal CertificationPhilip Norton
 
Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.DrupalCamp Kyiv
 
Drupal - Introduction to Building Library Web Site Using Drupal
Drupal - Introduction to Building Library Web Site Using DrupalDrupal - Introduction to Building Library Web Site Using Drupal
Drupal - Introduction to Building Library Web Site Using DrupalVibrant Technologies & Computers
 
One Man Band - Drupal Lightning Talks
One Man Band - Drupal Lightning TalksOne Man Band - Drupal Lightning Talks
One Man Band - Drupal Lightning TalksMark Jarrell
 
Minimalist Theming: How to Build a Lean, Mean Drupal 8 Theme
Minimalist Theming: How to Build a Lean, Mean Drupal 8 ThemeMinimalist Theming: How to Build a Lean, Mean Drupal 8 Theme
Minimalist Theming: How to Build a Lean, Mean Drupal 8 ThemeSuzanne Dergacheva
 
Drupal For Dummies
Drupal For DummiesDrupal For Dummies
Drupal For DummiesKoen Delvaux
 
#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)
#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)
#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)Konstantin Komelin
 
Making your Drupal fly with Apache SOLR
Making your Drupal fly with Apache SOLRMaking your Drupal fly with Apache SOLR
Making your Drupal fly with Apache SOLRExove
 
Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011
Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011
Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011camp_drupal_ua
 
Rapid site production with Drupal
Rapid site production with DrupalRapid site production with Drupal
Rapid site production with DrupalRob Sawyer
 
Building a Mobile Drupal Site
Building a Mobile Drupal SiteBuilding a Mobile Drupal Site
Building a Mobile Drupal SiteMark Jarrell
 
October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...
October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...
October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...Eric Sembrat
 
Performance on a budget (European Drupal Days 2015)
Performance on a budget (European Drupal Days 2015)  Performance on a budget (European Drupal Days 2015)
Performance on a budget (European Drupal Days 2015) Eugenio Minardi
 
Drupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDrupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDavid Lanier
 
One Drupal to rule them all - Drupalcamp London
One Drupal to rule them all - Drupalcamp LondonOne Drupal to rule them all - Drupalcamp London
One Drupal to rule them all - Drupalcamp Londonhernanibf
 

Was ist angesagt? (20)

10 New Things You Can Do with Drupal 8 Out-of-the-Box
10 New Things You Can Do with Drupal 8 Out-of-the-Box10 New Things You Can Do with Drupal 8 Out-of-the-Box
10 New Things You Can Do with Drupal 8 Out-of-the-Box
 
Drupal 7 Features - Introduction - Basics
Drupal 7 Features - Introduction - BasicsDrupal 7 Features - Introduction - Basics
Drupal 7 Features - Introduction - Basics
 
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course OverviewFrom Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
From Drupal 7 to Drupal 8 - Drupal Intensive Course Overview
 
Speedrun: Build a Website with Panels, Media, and More in 45 Minutes
Speedrun: Build a Website with Panels, Media, and More in 45 MinutesSpeedrun: Build a Website with Panels, Media, and More in 45 Minutes
Speedrun: Build a Website with Panels, Media, and More in 45 Minutes
 
Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8Custom Forms and Configuration Forms in Drupal 8
Custom Forms and Configuration Forms in Drupal 8
 
Acquia Drupal Certification
Acquia Drupal CertificationAcquia Drupal Certification
Acquia Drupal Certification
 
Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.Oleksandr Medvediev - Content delivery tools in Drupal 8.
Oleksandr Medvediev - Content delivery tools in Drupal 8.
 
Drupal - Introduction to Building Library Web Site Using Drupal
Drupal - Introduction to Building Library Web Site Using DrupalDrupal - Introduction to Building Library Web Site Using Drupal
Drupal - Introduction to Building Library Web Site Using Drupal
 
One Man Band - Drupal Lightning Talks
One Man Band - Drupal Lightning TalksOne Man Band - Drupal Lightning Talks
One Man Band - Drupal Lightning Talks
 
Minimalist Theming: How to Build a Lean, Mean Drupal 8 Theme
Minimalist Theming: How to Build a Lean, Mean Drupal 8 ThemeMinimalist Theming: How to Build a Lean, Mean Drupal 8 Theme
Minimalist Theming: How to Build a Lean, Mean Drupal 8 Theme
 
Drupal For Dummies
Drupal For DummiesDrupal For Dummies
Drupal For Dummies
 
#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)
#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)
#D8CX: Upgrade your modules to Drupal 8 (Part 1 and 2)
 
Making your Drupal fly with Apache SOLR
Making your Drupal fly with Apache SOLRMaking your Drupal fly with Apache SOLR
Making your Drupal fly with Apache SOLR
 
Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011
Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011
Roman Chernov.Panels custom layouts.DrupalCampKyiv 2011
 
Rapid site production with Drupal
Rapid site production with DrupalRapid site production with Drupal
Rapid site production with Drupal
 
Building a Mobile Drupal Site
Building a Mobile Drupal SiteBuilding a Mobile Drupal Site
Building a Mobile Drupal Site
 
October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...
October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...
October 2016 - USG Rock Eagle - Everything You Need to Know to Plan Your Drup...
 
Performance on a budget (European Drupal Days 2015)
Performance on a budget (European Drupal Days 2015)  Performance on a budget (European Drupal Days 2015)
Performance on a budget (European Drupal Days 2015)
 
Drupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 versionDrupal upgrades and migrations. BAD Camp 2013 version
Drupal upgrades and migrations. BAD Camp 2013 version
 
One Drupal to rule them all - Drupalcamp London
One Drupal to rule them all - Drupalcamp LondonOne Drupal to rule them all - Drupalcamp London
One Drupal to rule them all - Drupalcamp London
 

Andere mochten auch

FLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesFLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesMichel Alves
 
FLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactFLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactMichel Alves
 
FLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesFLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesMichel Alves
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP DevelopersUmut IŞIK
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactMichel Alves
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh ImpactMichel Alves
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modulestanoshimi
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...Alessandro Molina
 
TMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and ReportsTMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and ReportsMichel Alves
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Peter Kofler
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command LineBrian Richards
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development processPolished Geek LLC
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises Michel Alves
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsCarl Brown
 
FLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactFLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactMichel Alves
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con PythonManuel Pérez
 
Manipulating file in Python
Manipulating file in PythonManipulating file in Python
Manipulating file in Pythonshoukatali500
 
13 Graph Classes
13 Graph Classes13 Graph Classes
13 Graph Classespoffdeluxe
 

Andere mochten auch (20)

FLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - ExercisesFLTK Summer Course - Part VI - Sixth Impact - Exercises
FLTK Summer Course - Part VI - Sixth Impact - Exercises
 
FLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth ImpactFLTK Summer Course - Part VIII - Eighth Impact
FLTK Summer Course - Part VIII - Eighth Impact
 
FLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - ExercisesFLTK Summer Course - Part I - First Impact - Exercises
FLTK Summer Course - Part I - First Impact - Exercises
 
Git hooks For PHP Developers
Git hooks For PHP DevelopersGit hooks For PHP Developers
Git hooks For PHP Developers
 
FLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second ImpactFLTK Summer Course - Part II - Second Impact
FLTK Summer Course - Part II - Second Impact
 
FLTK Summer Course - Part VII - Seventh Impact
FLTK Summer Course - Part VII  - Seventh ImpactFLTK Summer Course - Part VII  - Seventh Impact
FLTK Summer Course - Part VII - Seventh Impact
 
Creating Custom Drupal Modules
Creating Custom Drupal ModulesCreating Custom Drupal Modules
Creating Custom Drupal Modules
 
Advanced Git
Advanced GitAdvanced Git
Advanced Git
 
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
EuroPython 2013 - FAST, DOCUMENTED AND RELIABLE JSON BASED WEBSERVICES WITH P...
 
TMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and ReportsTMS - Schedule of Presentations and Reports
TMS - Schedule of Presentations and Reports
 
Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)Code Refactoring - Live Coding Demo (JavaDay 2014)
Code Refactoring - Live Coding Demo (JavaDay 2014)
 
Using Git on the Command Line
Using Git on the Command LineUsing Git on the Command Line
Using Git on the Command Line
 
"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process"Git Hooked!" Using Git hooks to improve your software development process
"Git Hooked!" Using Git hooks to improve your software development process
 
FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises FLTK Summer Course - Part II - Second Impact - Exercises
FLTK Summer Course - Part II - Second Impact - Exercises
 
Introduction to Git Commands and Concepts
Introduction to Git Commands and ConceptsIntroduction to Git Commands and Concepts
Introduction to Git Commands and Concepts
 
FLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third ImpactFLTK Summer Course - Part III - Third Impact
FLTK Summer Course - Part III - Third Impact
 
Servicios web con Python
Servicios web con PythonServicios web con Python
Servicios web con Python
 
Manipulating file in Python
Manipulating file in PythonManipulating file in Python
Manipulating file in Python
 
Code of Conduct_formatted
Code of Conduct_formattedCode of Conduct_formatted
Code of Conduct_formatted
 
13 Graph Classes
13 Graph Classes13 Graph Classes
13 Graph Classes
 

Ähnlich wie Drupal Module Development Hands-On Guide - Build Custom TweetScope Module

Drupal module development
Drupal module developmentDrupal module development
Drupal module developmentRachit Gupta
 
Intro to Drupal Module Developement
Intro to Drupal Module DevelopementIntro to Drupal Module Developement
Intro to Drupal Module DevelopementMatt Mendonca
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireJeff Fox
 
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfOrtus Solutions, Corp
 
Top 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal projectTop 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal projectIztok Smolic
 
Drupal Theming for Developers
Drupal Theming for DevelopersDrupal Theming for Developers
Drupal Theming for DevelopersIan Carnaghan
 
Introduction To Drupal
Introduction To DrupalIntroduction To Drupal
Introduction To DrupalLauren Roth
 
Drupal: Reusing functionality
Drupal: Reusing functionalityDrupal: Reusing functionality
Drupal: Reusing functionalityRaymond Muilwijk
 
Drupal training-1-in-mumbai
Drupal training-1-in-mumbaiDrupal training-1-in-mumbai
Drupal training-1-in-mumbaivibrantuser
 
Beginner's guide to drupal
Beginner's guide to drupalBeginner's guide to drupal
Beginner's guide to drupalmayank.grd
 
Drupal: an Overview
Drupal: an OverviewDrupal: an Overview
Drupal: an OverviewMatt Weaver
 
Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011
Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011
Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011camp_drupal_ua
 
Linked Data Publishing with Drupal (SWIB13 workshop)
Linked Data Publishing with Drupal (SWIB13 workshop)Linked Data Publishing with Drupal (SWIB13 workshop)
Linked Data Publishing with Drupal (SWIB13 workshop)Joachim Neubert
 
Easy Drupal Project Deployment With Features Module & Drush
Easy Drupal Project Deployment With Features Module & DrushEasy Drupal Project Deployment With Features Module & Drush
Easy Drupal Project Deployment With Features Module & DrushQArea
 
Contributions: what they are and how to find them
Contributions: what they are and how to find themContributions: what they are and how to find them
Contributions: what they are and how to find themPedro Cambra
 
Absolute Beginners Guide to Drupal
Absolute Beginners Guide to DrupalAbsolute Beginners Guide to Drupal
Absolute Beginners Guide to DrupalRod Martin
 
Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4Gerke Max Preussner
 

Ähnlich wie Drupal Module Development Hands-On Guide - Build Custom TweetScope Module (20)

Drupal module development
Drupal module developmentDrupal module development
Drupal module development
 
Intro to Drupal Module Developement
Intro to Drupal Module DevelopementIntro to Drupal Module Developement
Intro to Drupal Module Developement
 
Modular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter BonfireModular PHP Development using CodeIgniter Bonfire
Modular PHP Development using CodeIgniter Bonfire
 
72d5drupal
72d5drupal72d5drupal
72d5drupal
 
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
 
Top 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal projectTop 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal project
 
Drupal Skils Lab 302Labs
Drupal Skils Lab 302Labs Drupal Skils Lab 302Labs
Drupal Skils Lab 302Labs
 
Drupal Theming for Developers
Drupal Theming for DevelopersDrupal Theming for Developers
Drupal Theming for Developers
 
Introduction To Drupal
Introduction To DrupalIntroduction To Drupal
Introduction To Drupal
 
Drupal: Reusing functionality
Drupal: Reusing functionalityDrupal: Reusing functionality
Drupal: Reusing functionality
 
Drupal training-1-in-mumbai
Drupal training-1-in-mumbaiDrupal training-1-in-mumbai
Drupal training-1-in-mumbai
 
Drupal 8 Modules
Drupal 8 ModulesDrupal 8 Modules
Drupal 8 Modules
 
Beginner's guide to drupal
Beginner's guide to drupalBeginner's guide to drupal
Beginner's guide to drupal
 
Drupal: an Overview
Drupal: an OverviewDrupal: an Overview
Drupal: an Overview
 
Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011
Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011
Anna Fedoruk.Theworkflow.DrupalCamp Kyiv 2011
 
Linked Data Publishing with Drupal (SWIB13 workshop)
Linked Data Publishing with Drupal (SWIB13 workshop)Linked Data Publishing with Drupal (SWIB13 workshop)
Linked Data Publishing with Drupal (SWIB13 workshop)
 
Easy Drupal Project Deployment With Features Module & Drush
Easy Drupal Project Deployment With Features Module & DrushEasy Drupal Project Deployment With Features Module & Drush
Easy Drupal Project Deployment With Features Module & Drush
 
Contributions: what they are and how to find them
Contributions: what they are and how to find themContributions: what they are and how to find them
Contributions: what they are and how to find them
 
Absolute Beginners Guide to Drupal
Absolute Beginners Guide to DrupalAbsolute Beginners Guide to Drupal
Absolute Beginners Guide to Drupal
 
Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4Plug-ins & Third-Party SDKs in UE4
Plug-ins & Third-Party SDKs in UE4
 

Kürzlich hochgeladen

General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Kürzlich hochgeladen (20)

General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Drupal Module Development Hands-On Guide - Build Custom TweetScope Module

  • 1. Drupal Module Development “Hands-on” Anil Sagar Gaurav Kumar Blisstering Solutions
  • 2. Table Of Contents 1. Drupal Architecture …………………………………………………….03 2. Database Architecture ……………………………………………….11 3. Module Types …………………………………………………………….14 4. Hands on Module “TweetScope” ……………………………….21 5. Module Architecture ………………………………………………….26 6. Introduction of hooks ………………………………………………..33 7. hook_menu ………………………………………………………………..37 8. Form API …………………………………………………………………….43 9. Permissions and Access Control ………………………………..51 10. Schema API ………………………………………………………………56 11. Modify an existing form …………………………………………..62 12. hook_nodeapi ………………………………………………………….65 13. hook_block ………………………………………………………………70 14. Look & Feel ………………………………………………………………75 15. Bonus Topics: Eclipse, Xdebug, Coder, Firebug ………..80 16. Question and Answers ……………………………………………..85
  • 3. 1. Drupal Architecture Technology Stack L(/W)AMP Code Base (Drupal 6.16) Database 3
  • 4. Technology Stack Language Database Abstraction Layer Database Web Server Operating System 4
  • 5. System Requirements Web Server: • Apache: Drupal will work on Apache 1.3 or Apache 2.x hosted on UNIX/Linux, OS X or Windows. • Microsoft IIS: Drupal core will work using IIS 5, IIS 6, or IIS 7. Database: • MySQL: Drupal 6 supports MySQL 4.1 or higher. Recommended by drupal.org • PostgreSQL: Drupal supports 7.4 or higher. PHP: • Recommended: PHP 5.2.x 5
  • 6. File Structure all default 6
  • 7. includes folder: Contains libraries of common function that Drupal does. • modules folder: Contains the core modules, with each module in its own folder. • profiles folder: Contains different installation profiles for a site. If there are other profiles besides the default profile in this subdirectory, Drupal will ask you which profile you want to install when first installing your Drupal site. • scripts folder: Contains scripts for checking syntax, cleaning up code, running Drupal from the command line, and handling special cases with cron. 7
  • 8. sites folder: i. Contains the user modifications to Drupal in the form of settings, modules, and themes. When you add modules to Drupal from the contributed modules repository or by writing your own, they go into sites/all/modules. ii. This keeps all your Drupal modifications within a single folder. Inside the sites directory there will be a subdirectory named default that holds the default configuration file for your Drupal site—default.settings.php. iii. The Drupal installer will modify these original settings based on the information you provide and write a settings.php file for your site. The default directory is typically copied and renamed to the URL of your site by the person deploying the site, so your final settings file would be at sites/www.example.com/settings.php. 8
  • 9. themes folder: The themes folder contains the template engines and default themes for Drupal. Additional themes you download or create should not go here; they go into sites/all/themes. • cron.php file: cron.php is used for executing periodic tasks, such as pruning database tables and calculating statistics. • index.php: main entry point. • install.php: main entry point for the Drupal installer. • update.php: Updates the database schema after a Drupal version upgrade. 9
  • 10. xmlrpc.php: Receives XML-RPC requests and may be safely deleted from deployments that do not intend to receive XML- RPC requests. • robots.txt: Default implementation of the robot exclusion standard. 10
  • 11. 2. Database Architecture Configuration Content Changes Changes 11
  • 12. Database Architecture For example some of the tables which stores configuration related information are as follows: • blocks: Block. This stores information about blocks provided by every module installed, including custom blocks. • blocks role: Block. Stores the roles permitted to view blocks in the system. • menu: Menu. Storage of menu module customizations. • system: System. Information about installed modules. 12
  • 13. Database Architecture Some tables which holds content information • node Node. The main table for storing general node information, including the title, node number, dates, workflow state, but it does not store most of the actual content. • node_revisions Node. Stores information about node revisions, including the main content of the node. • users User. User records. 13
  • 14. 3. Module Types Core Modules Contributed Modules Custom Modules 14
  • 15. Module Types Drupal modules are basically categorized into three types 1. Core Modules: Drupal comes with 31 core modules, which address everything from basic functions such as user management (the User module), logging (the Watchdog module), and analysis of access to the site (the Statistics module) to advanced features such as managing a hierarchical series of collaborative pages that can be versioned and moderated (the Book module). Becoming familiar with these modules and mastering their usage will help you get the most out of Drupal and create powerful web sites. 15
  • 16. Required Core Modules • Block: Restricted to web administrator access only. • Filter: Authorized users and web administrators can choose from either Filtered or Full HTML Input formats. • Node: Responsible for content. • System: Responsible for cron and caching. Primary Web Site Admin. only. • User: User Management, Roles, Permissions. Web administrator access only. 16
  • 17. Optional Core Modules Drupal core comes with optional modules that can be enabled if required. • Aggregator: publishing syndicated content • Blog: a blog for every user • BlogApi: post from blog tools • Book: structured document publishing • Color: Allows the user to change the color scheme of certain themes • Comment: allow comments on content • Contact: a way for users to get in touch • Content translation: translating posts to different languages • Locale: multi-language support • Menu: customize site navigation • Open ID • Path: readable URLs 17
  • 18. 2. Contributed Modules: • Although core modules can provide the basics for your site, and can in some cases get you pretty far, the real power in Drupal comes from its vast array of community-contributed modules. • You can browse and download all contributed modules from http://drupal.org/project/Modules • Once you’ve downloaded and extracted the module directory, place it into the sites/all/modules/contrib directory and your new module should appear on the Module administration page www.yoursite.com/admin/build/modules. 18
  • 19. Some Widely Used Contributed Modules: • Views This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. • Content Construction Kit (CCK) Most content in a Drupal site will come from instances of Content Types. The Content Construction Kit allows you to add custom fields to any of the content types using a web interface. • Google Analytics Adds the Google Analytics web statistics tracking system to your website. 19
  • 20. 3. Custom Modules • To extend functionality of contributed modules. • To build features that are specific to your site. • To build features that are not available through core or contributed modules. 20
  • 21. 4. Hands On Module “TweetScope” What is tweetscope ? • Display node related tweets in your node display page. Why a custom module ? • No existing contributed module has this feature out of the box. 21
  • 22. Lets Build A Module “TweetScope Module” Specify Display Twitter keywords Find Results Theme the Results in node related to a From Twitter results page node 22
  • 23. TweetScope Module Requirements • Administrator can configure which are all node types he want to display related tweets, using simple form. • Database to store keywords and node id for fetching twitter results. • Altering the node add form to create a simple text field which captures keyword related to particular node. • A simple block which displays related tweets of a node. 23
  • 24. Tasks In our module we are going to accomplish the following tasks: 1. Creating a simple administrator settings page using hook_menu. 2. A simple form using hook_form in the above page to store tweetscope admin settings. 3. How to validate form using validate and submit functions. 4. How to display notification messages and errors using drupal_set_message. 5. How to define permissions to restrict access to the administrator page that we created in step 1. 6. How to create a simple schema for storing keywords related to a node using hook_schema in .install file and hook_install and hook_uninstall functions to install and uninstall schema. 24
  • 25. Tasks (Continued) 7. How to alter existing node add form using form_alter to add additional field which captures keyword related to a particular node. 8. How to update the keywords for a particular node using hook_nodeapi 9. How to create a simple block using hook_block to display twitter results. 10. How to theme a block using hook_theme. 25
  • 26. 5. Module Architecture “The building blocks of a module” The .module The .info file The .install file file 26
  • 27. Module Architecture 1. In Drupal, every module is contained in its own directory. This simplifies organization; all of the module's files are located in one place. 2. To keep naming consistent throughout the module (a standard in Drupal), we will name our directory with the module name. 3. Basic files that are required for every module are : 4. .info file 5. .module file 6. Some optional files depending on type of functionality module required are: 7. .install file .js file 8. .inc file (Include file) .css file 27
  • 28. .info file • Drupal uses .info files (aka, "dot info files") to store metadata about themes and modules. Various Drupal components use the information in this file for module management. • The .info file should have the same name as the .module file and reside in the same directory. For example, if our module is named tweetscope.module then your .info file should be named tweetscope.info. 28
  • 29. tweetscope.info File ; $Id$ name = “Tweetscope” description = “Provides tweets related to a node.” core = 6.x ;$id$ The first line of the file is, at first glance, the most cryptic. However, its function is mundane: it is a placeholder for Drupal's CVS server. name (Required) The displayed name of your module. It should follow the Drupal capitalization standard: only the first letter of the first word is capitalized ("Example module"). Spaces are allowed as the name is used mainly for the display purposes. name = “Tweetscope" 29
  • 30. tweetscope.info File description (Required) A short, preferably one line description that will tell the administrator what this module does on the module administration page. Remember, overly long descriptions can make this page difficult to work with, so please try to be concise. This field is limited to 255 characters. description = "Provides tweets related to a node.“ core (Required) The version of Drupal that your module is for. For Drupal 6 this would be 6.x, Drupal 7 would be 7.x, etc. Note that modules cannot specify the specific version of a branch of Drupal. 6.x is correct 6.2 is not. core = 6.x 30
  • 31. tweetscope.info File .info module meta data is used to display module related information in modules list page 31
  • 32. tweetscope.module File • The purpose of a module is to extend Drupal's capabilities. • A module is a bundle of PHP code and supporting files that use Drupal's APIs and architecture to integrate new functional components into the Drupal framework. How Does Drupal Communicate with the module ? This is done through hook mechanism in Drupal • 32
  • 33. 6. Introduction to Hooks What are hooks? Why should I care? 33
  • 34. What are hooks? • A hook is really nothing more than a function that matches the pattern of a call to the module functions . • You can say that hook is a simple callback function that is called on specific events. • Pattern modulename_hookname() • For example, if you want to do some operation on user login, say sending an email to administrator on user logins into the site, then no need to change the code in user module. • Implement hook_user on your own module say “alert” by defining function in your module file called alert_user and write code to send an email to administrator here. 34
  • 35. Why should I care? • Modules Extends it’s functionality through hook system. • One module communicates through other module through hooks. • The Hooks API provides a common naming standard for hooks, allowing developers to implement them in custom modules without needing to engage in extensive programming. • The Hooks API allows developers to create their own hooks that other modules can access, that leverage the same techniques used in core Drupal. • Many hooks are state aware, and operate differently depending on what Drupal is actually doing when the hook is triggered. 35
  • 36. Our First Coding Task 1. Creating a simple administrator settings page using hook_menu. • Path of our administration page is admin/settings/tweetscope • Title of the pages is Tweetscope administrator settings. • This page should display settings form to configure the nodes that can able to display tweets related to that node. • We need to restrict access to this page only for specific roles of users by creating permissions. 36
  • 37. 7. hook_menu “The drupal page request handler” 37
  • 38. hook_menu • hook_menu defines menu items and page callbacks. • This hook enables modules to register paths, which determines whose requests are to be handled. Depending on the type of registration requested by each path, a link is placed in the the navigation block and/or an item appears in the menu administration page. • You can check more about this hook at http://api.drupal.org/api/function/hook_menu 38
  • 39. tweetscope_menu() function tweetscope_menu() { $items = array(); $items['admin/settings/tweetscope'] = array( 'title' => 'Tweetscope Settings', 'description' => 'Contains settings for my module', 'page callback' => 'drupal_get_form', 'page arguments' => array('tweetscope_form'), 'access callback' => 'user_access', 'access arguments' => array('administer tweetscope') ); return $items; } 39
  • 40. tweetscope_menu() • The first line of function is function declaration, which follows pattern modulename_hookname. • hook_menu returns an array of menu items. Each menu item has a key corresponding to the Drupal path being registered. The item is an associative array that may contain different key-value pairs. • The second line defines $items array. In the next line we defined a new item by defining path “admin/settings/tweetscope” as key of the array. • We defined other parameters as key – value pairs in an associate array. 40
  • 41. tweetscope_menu() • "access callback": A function returning a boolean value that determines whether the user has access rights to this menu item. Defaults to user_access() unless a value is inherited from a parent menu item. • "access arguments": An array of arguments to pass to the access callback function. 41
  • 42. Time To Extend • A simple form using hook_form in the above page to store tweetscope admin settings. • How to validate form using validate and submit functions. • How to display notification messages and errors using drupal_set_message. • Display all node types as checkboxes to select node types that will have related tweets. • Validate form such that at least one node type is enabled for displaying related tweets. • Set notification messages on failure of above validation. • On successful validation save the results and display successful notification using drupal_set_message. 42
  • 43. 8. The FORM API hook_form Form API elements Form Validate Form Submit drupal_set_message drupal_set_error 43
  • 44. tweetscope_form() function tweetscope_form() { $form = array(); $form['settings'] = array( '#type' => 'fieldset', '#title' => 'TweetScope Settings' ); $form['settings']['node-types'] = array( '#type' => 'checkboxes', '#options' => node_get_types('names'), '#title' => 'Node Types', '#description' => 'Tweetscope will be available for the follwing content types', '#default_value' => variable_get('tweetscope_node_types', array()) ); $form['submit'] = array( '#type' => 'submit', '#value' => 'Submit' ); return $form; } 44
  • 45. tweetscope_form() • tweetscope_form function is called through menu page callback function drupal_get_form which takes argument form_id as tweetscope_form • Return value is an array containing the form elements to be displayed in the form. 45
  • 46. tweetscope_form() We defined three form elements in our form function. • First element fieldset specifes For form groups, the '#type' parameter is set to 'fieldset', and notice how the ‘settings' form group is made into a collapsed form group with the addition of a few attributes. • Second element gives all node types selectable as checkboxes, the '#type' parameter is set to ‘checkboxes', and options are populated using node_get_types function which returns an array of node type names. • Last one is submit form element, the '#type' parameter is set to ‘submit', and the label is set to “Submit” using #value parameter. 46
  • 47. tweetscope_form_validate function tweetscope_form_validate($form, &$form_state) { $flag = 0; foreach($form_state['values']['node-types'] as $key => $value) { if($key === $value) { $flag = 1; } } if($flag == 0) { form_set_error('settings','Select atleast one value'); } } 47
  • 48. tweetscope_form_validate • Accepts $form_state a keyed array containing the current state of the form as parameter. The current user-submitted data is stored in $form_state['values'], though form validation functions are passed an explicit copy of the values for the sake of simplicity. • We check for at least one node type is selected, by comparing key - value pairs. • If none of the node types are selected then we set an error message using form_set_error function. • If validation passes successfully, control is passed to tweetscope_form_submit function. 48
  • 49. tweetscope_form_submit function tweetscope_form_submit($form, &$form_state) { variable_set('tweetscope_node_types', $form_state['values']['node- types']); drupal_set_message('Your form has been submitted'); } 49
  • 50. tweetscope_form_submit • Accepts $form_state a keyed array containing the current state of the form as parameter. • We save the settings in a variable using variable_set function which takes variable name as first argument and value as second argument. • Variable value can be retrieved using variable_get function. • After storing the result successfully we display the notification message using drupal_set_message function which takes message as an argument. 50
  • 51. 9. Permissions, Access Control “The safe way is the only way” 51
  • 52. Permissions, Access Control hook_perm http://api.drupal.org/api/function/hook_perm function tweetscope_perm() { return array('administer tweetscope'); } • Define user permissions. • This hook can supply permissions that the module defines, so that they can be selected on the user permissions page and used to grant or restrict access to actions the module performs. Return value An array of permission strings. 52
  • 53. Permissions, Access Control Once hook_perm is defined we can see the permissions settings at admin/user/permissions 53
  • 54. .install file • A .install file is run the first time a module is enabled, and is used to run setup procedures as required by the module. The most common task is creating database tables and fields. The .install file does not have any special syntax. It is merely a PHP file with a different extension. • Implements hook_install which installs table when module is enabled. • Implements hook_uninstall which drops table when module is uninstalled. • .install files are also used to perform updates when a new version of a module needs it. 54
  • 55. Tweetscope Table: Tweetscope table contains two fields. The fields are described as below. nid: Primary key of the table which stores unique id of node. Data Type: int Length : 10 keywords: Stores keywords related to a node. Data Type: Varchar Length: 255 55
  • 56. 10. The Schema API http://api.drupal.org/api/group/schemaapi/6 hook_schema hook_install hook_uninstall 56
  • 57. tweetscope_schema • A Drupal schema definition is an array structure representing one or more tables and their related keys and indexes. • By implementing hook_schema() and specifying the tables your module declares, you can easily create and drop these tables on all supported database engines. • Drupal supports MySQL and PostgreSQL databases. Return value A schema definition structure array. For each element of the array, the key is a table name and the value is a table structure definition. 57
  • 58. tweetscope_schema function tweetscope_schema() { $schema = array(); $schema['tweetscope_node'] = array( 'description' => 'Stores node to keyword mapping', 'fields' => array( 'nid' => array( 'type' => 'int', 'not null' => TRUE ), 'keywords' => array( 'type' => 'varchar', 'length' => '255', 'default' => '' ) ), 'primary key' => array('nid') ); return $schema; 58 }
  • 59. hook_install() • The hook will be called the first time a module is installed. • Installs the schema that we created earlier. • Creates necessary tables that we defined in hook_schema. function tweetscope_install() { drupal_install_schema('tweetscope'); } • drupal_install_schema($module) Create all tables that a module defines in its hook_schema() 59
  • 60. hook_uninstall() • Remove any tables or variables that the module sets. • The uninstall hook will fire when the module gets uninstalled. • Drops tables that we defined in hook_schema. function tweetscope_uninstall() { drupal_uninstall_schema('tweetscope'); } • drupal_uninstall_schema($module) Drops all tables that a module defines in its hook_schema() 60
  • 61. Altering Node Forms • As per tweetscope node settings, we need to alter node add forms with new text field which captures keyword related to a node. • Display the keyword in node edit form if a particular node is already configured with a related keyword. • On insert or update of a node we need to insert or update keyword into tweetscope table that we created earlier using hook_schema. 61
  • 62. 11.Modify an existing form hook_form_alter http://api.drupal.org/api/function/hook_form_alter 62
  • 63. hook_form_alter(&$form, &$form_state, $form_id) • Perform alterations before a form is rendered. Parameters • $form Nested array of form elements that comprise the form. • $form_state A keyed array containing the current state of the form. • $form_id String representing the name of the form itself. 63
  • 64. tweetscope_form_alter(&$form, &$form_state, $form_id) function tweetscope_form_alter(&$form, &$form_state, $form_id) { $node_types = variable_get('tweetscope_node_types', array()); foreach ($node_types as $key => $value) { if ($value !== 0) { if ($form_id == $key.'_node_form') { $form['keywords'] = array( '#type' => 'textfield', '#title' => 'TweetScope Keywords', '#description' => 'Specify your twitter keywords here.', '#default_value' => db_result(db_query("SELECT keywords FROM {tweetscope_node} where nid = %d", arg(1))), '#size' => '60', ); } } } } 64
  • 65. 12. Node operations “The king of all hooks” hook_nodeapi http://api.drupal.org/api/function/hook_nodeapi/6 65
  • 66. hook_nodeapi • Act on nodes defined by other modules. Parameters • &$node: The node the action is being performed on. • $op: What kind of action is being performed. Possible values: • "delete": The node is being deleted. • "insert": The node is being created (inserted in the database). • "update": The node is being updated. • "view": The node content is being assembled before rendering. The module may add elements $node->content prior to rendering. • $a3 For "view", passes in the $teaser parameter from node_view(). For "validate", passes in the $form parameter from node_validate(). • $a4 For "view", passes in the $page parameter from node_view(). 66
  • 67. Case “insert” • Find the node types that currently have tweetscope feature enabled. • Compare the node types with the node that is ready to submit. • If matches retrieve the value of keyword textfield that we added to node add form using hook_form_alter • Store the result into tweetscope table with nid and keyword. Case “update” • Update the result stored in tweetscope table. 67
  • 68. tweetscope_nodeapi function tweetscope_nodeapi(&$node, $op , $a3, $a4) { $node_types = variable_get('tweetscope_node_types', array()); foreach ($node_types as $key => $value) { if ($value !== 0) { if ($node->type == $key) { switch ($op) { case 'insert': db_query("INSERT INTO {tweetscope_node} (nid, keywords) VALUES (%d, '%s')", $node->nid, $node->keywords); break; case 'update': db_query("UPDATE {tweetscope_node} SET keywords = '%s' where nid = %d", $node->keywords, $node->nid); break; } } } } 68 }
  • 69. Time to see results !! • Implement hook_block to see results in a block. • Enable the block in node display pages. • Retrieve the keyword associated with a particular node from tweetscope table. • Retrieve the results from twiiter using twiiter search API using json format. • Decode the results from json to array and display the results. • Theme the results using hook_theme function and Cascading Style Sheets 69
  • 70. 13. The Module’s Block hook_block http://api.drupal.org/api/function/hook_block/6 70
  • 71. hook_block($op = 'list', $delta = 0, $edit = array()) • Declare a block or set of blocks. Parameters • $op What kind of information to retrieve about the block or blocks. Possible values: • 'list': A list of all blocks defined by the module. • 'configure': Configuration form for the block. • 'save': Save the configuration options. • 'view': Process the block when enabled in a region in order to view its contents. 71
  • 72. hook_block($op = 'list', $delta = 0, $edit = array()) • $delta Which block to return (not applicable if $op is 'list'). Although it is most commonly an integer starting at 0, this is not mandatory. For instance, aggregator.module uses string values for $delta • $edit If $op is 'save', the submitted form data from the configuration form. 72
  • 73. hook_block Case “list” • Returns an array of blocks which holds information of block. function tweetscope_block($op = 'list', $delta = 0, $edit = array()) { switch ($op) { case 'list': $blocks[0]['info'] = "Twitter Results"; return $blocks; break; } } 73
  • 74. Case “view” • Returns content that will be rendered on block. case 'view': switch ($delta) { case 0: $keyword = db_result(db_query("SELECT keywords FROM {tweetscope_node} where nid = %d", arg(1))); if ($keyword != '') { $twitter_results = json_decode(file_get_contents('http://search.twitter.com/search.json?q='.$keyword)); foreach($twitter_results->results as $tweet => $tweet_value) { $blocks['content'] .= theme('tweetscope_tweet', $tweet_value->text, $tweet_value->from_user, $tweet_value->profile_image_url); } } else { $blocks['content'] = 'No twitter results exist for this page!!'; } $blocks['subject'] = 'Twitter Results'; 74 return $blocks;
  • 75. 14. Look & Feel hook_theme http://api.drupal.org/api/function/hook_theme/6 75
  • 76. hook_theme • To register a module theme function we need to implement hook_theme. • hook_theme defines new theme function called tweetscope_tweet which themes the output of themes. • hook_theme return an associative array which has theme function name as key and arguments as an associative array. • Implementation of theme function is writing a function with pattern theme_themefunctionname that we defined in hook_theme. 76
  • 77. tweetscope_theme function tweetscope_theme() { return array( 'tweetscope_tweet' => array( 'arguments' => array('tweet' => NULL, 'tweet_user' => NULL, 'img' => NULL), ), ); } • Defines a new theme function – tweetscope_tweet • Accepts three parameters: tweet, tweet_user. img 77
  • 78. Implementation of theme_tweetscope_tweet • Return the output wrapped inside div tags. • Write Cascading Style Sheets to theme the output. • Include Cascading Style Sheet in our module. • Return the themed output. 78
  • 79. Implementation of theme_tweetscope_tweet function theme_tweetscope_tweet($tweet, $tweet_user, $img) { $module_path = drupal_get_path('module', 'tweetscope'); $full_path = $module_path .'/tweetscope.css'; drupal_add_css($full_path); $output = '<div id="tweet-image"><img src="'. $img .'"></img></div><div id="tweetscope-tweet">'. $tweet .'</div><div id="tweet-user"><strong>By </strong>'. $tweet_user .'</div>'; return $output; } 79
  • 80. 15. Bonus Topics Ecplise Coder Xdebug Firebug 80
  • 81. Eclplise PDT http://download.eclipse.org/tools/pdt/downloads/ • Editor - code completion and syntax coloring • Faster development, fewer coding errors • Editor - auto line-numbering, code collapsing • Debugging • Visual Layout - alignment, spacing, sizing options. 81
  • 82. Coder • Indentation Check • Coding Standards • Security Guidelines • Warnings and Errors 82
  • 83. Xdebug • Install Xdebug • Configure php.ini settings • Configure your eclipse • Break Points • Happy Debugging 83
  • 84. JavaScript Debugging and Profiling • "Live" editing and inspection of (X)HTML code • CSS editing, modification and visual highlighting. • HTTP Related Network Monitoring 84
  • 86. Anil Sagar (anil.sagar @ blisstering.com) Gaurav Kumar (gaurav.kumar@blisstering.com) Blisstering Solutions (www.blisstering.com) 86