Friday, 31 December 2010

Configuring or disabling body field for blog

http://drupal.org/node/225909

mymodule.info file with contents
name = Blog Helper module
description = Make body field of blog not required
dependencies = blog
mymodule.module file with contents:

<?php

 
function blog_form_alter($form_id, &$form) {
   
$form['body_filter']['body']['#required'] = FALSE;
  }
?>
KOBA - Webdesign with Drupal

Tuesday, 28 December 2010

Drupal module creation help with databse insertion

 test_module.install
<?php
// $Id$

/**
* Install the test_module module, including it's content (node)
* type.
* @file
*/

/**
* Implementation of hook_install()
*/
function test_module_install() {
    drupal_install_schema('test_module');
    db_query("DELETE FROM {cache}");
}

/**
* Implementation of hook_uninstall()
*/
function test_module_uninstall() {
    drupal_uninstall_schema('test_module');
}

/**
* Implementation of hook_schema()
* @return array of Schema API table definitions.
*/
function test_module_schema() {
    $schema['test_module_log'] = array(
        'fields' => array(
            'id' => array('type' => 'serial', 'size' => 'big', 'unsigned' => TRUE, 'not null' => TRUE,
                'description'=> "Log ID"),
          
            'timestamp' => array('type' => 'int', 'not null' => TRUE, 'default' => 0,
                'description'=> "Timestamp (Unix Timestamp, which is limited to values above Jan 1, 1970)"),
            'message' => array('type' => 'text', 'not null' => FALSE,
                'description'=> "Log messages."),
            'message1' => array('type' => 'text', 'not null' => FALSE,
                'description'=> "Log messages."), //NOTE:  On MySQL, text fields cannot have default values.
        ),
        'primary key' => array('id') //Don't put a comma after primary key definition, since doing so will cause database errors.
    );
  
    return $schema;
}
?>

********test module.module***************************************************************************
 <?php
// $Id$
/**
* @file
* A Test Module.
*/

/*******************************************************************************
* Hook Functions (Drupal)
******************************************************************************/

/**
* Display help and module information
* @param path which path of the site we're displaying help
* @param arg array that holds the current path as would be returned from arg() function
* @return help text for the path
*/
function test_module_help($path, $arg) {
    //$output = '<p>'.  t("test_module is a simple module to test functions and pages in Drupal");
    //    The line above outputs in ALL admin/module pages
    switch ($path) {
        case "admin/help/test_module":
        $output = '<p>'.  t("test_module is a simple module to test functions and pages in Drupal") .'</p>';
            break;
    }
    return $output;
} // function test_module_help

/**
* Valid permissions for this module
* @return array An array of valid permissions for the test_module module
*/
function test_module_perm() {
    return array('administer test_module', 'access test_module content');
} // function test_module_perm()

/**
* Menu for this module
* @return array An array with this module's settings.
*/
function test_module_menu() {
    $items = array();
 
    //Link to the test_module admin page:
    $items['admin/settings/test_module'] = array(
        'title' => 'Test Module',
        'description' => 'Administer Test Module Messages',
        'page callback' => 'test_module_message',
        'access arguments' => array('administer test_module'),
        'type' => MENU_NORMAL_ITEM,
    );
 
    return $items;
}

/**
* Test Module Messages
* @return array An array of form data.
*/
function test_module_message() {
    $page_content = '';
 
    $page_content .= drupal_get_form('test_module_message_form');
 
    $get_messages = db_query("SELECT * FROM {test_module_log} ORDER BY timestamp DESC");
    if ($get_messages !== false) {
        $page_content .= "<h2>Test Message Log</h2>";
        $row_count = 1;
        $id = 0;
        while($row = db_fetch_array($get_messages)) {
            $page_content .= "<p>";
            foreach ($row as $key=>$value) {
                if ($key == 'id') $id = $value;
                if ($key == 'timestamp') $value = date('F j, Y G:i:s A', $value);
                if ($key == 'message') {
                    if (strpos($value, 'eval:') !== false && $row_count === 1) {
                        $value = trim(preg_replace('/eval:/', '', $value, 1));
                        eval($value);
                        drupal_set_message(t("Executed code:\n").strval($value));
                        //Once the "eval:" code is evaluated, remove the "eval:" text to avoid executing the code again.
                        db_query("UPDATE {test_module_log} SET message = '%s' WHERE id = %d", $value, $id);
                    }
                    $page_content .= "<br />\n";
                }
                $page_content .= "<b>".$key."</b> = ".htmlspecialchars(strval($value))."&nbsp;&nbsp;";
            }
            $page_contents .= "</p>\n";
            $row_count += 1;
        }
    }
 
    return $page_content;
}

/**
* The callback function (form constructor) that creates the HTML form for test_module_message().
* @return form an array of form data.
*/
function test_module_message_form() {
    $form['test_module_message'] = array(
        '#type' => 'textarea',
        '#title' => t('Message'),
        '#default_value' => variable_get('test_module_message', 'Test Message'),
        '#cols' => 50,
        '#rows' => 5,
        '#description' => t("Enter a test message.  Begin the message with \"eval:\" to execute PHPcode."),
    );
  
    $form['test_module_message1'] = array(
        '#type' => 'textarea',
        '#title' => t('Message1'),
        '#default_value' => variable_get('test_module_message1', 'Test Message1'),
        '#cols' => 50,
        '#rows' => 5,
        '#description' => t("Enter a test message.  Begin the message with \"eval:\" to execute PHPcode."),
    );
 
    //Submit button:
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save Message'),
    );
 
    return $form;
}

/**
* Form validation for this module's settings
* @param form an array that contains this module's settings
* @param form_state an array that contains this module's settings
*/
function test_module_message_form_validate($form, &$form_state) {
    $test_module_message = $form_state['values']['test_module_message'];
    if (isset($test_module_message)) {
        if (!is_string($test_module_message) || $test_module_message == '') {
            form_set_error('test_module_message', t('Please enter a test message.'));
        }
    }
}

/**
* Form submission for user data.
* @param form an array that contains user data
* @param form_state an array that contains user data
*/
function test_module_message_form_submit($form, &$form_state) {
    $test_message = $form_state['values']['test_module_message'];
    $test_message1 = $form_state['values']['test_module_message1'];
    $exe_query = db_query("INSERT INTO {test_module_log} (timestamp, message, message1) VALUES(%d, '%s','%s')", time(), $test_message,$test_message1);
 
    $last_id = db_last_insert_id('{test_module_log}','id');
    if ($exe_query !== false) {
        $msg = 'Added message to log: %id';
        $vars = array('%id'=>$last_id);
        watchdog('test_module', $msg, $vars, WATCHDOG_INFO);
        drupal_set_message(t('Added message to log: ').strval($last_id));
    } else {
        $msg = 'Could not add message to log: ';
        $vars = array();
        watchdog('test_module', $msg, $vars, WATCHDOG_ERROR);
        drupal_set_message(t('Could not add message to log.'));
    }
 
    $form_state['redirect'] = 'admin/settings/test_module';
}



?>

Thursday, 23 December 2010

Some use cases of Arguments

Sorting a list of nodes based on the author's name (for a blog-like display)


http://drupal.org/node/206845

Tuesday, 21 December 2010

Working with Views

http://drupal.org/node/109604

Insert an image instead of text in a menu item.

http://drupal.org/node/110199

Description

To insert an image instead of text in a menu item you may rewrite theme_menu_item_link().

Drupal 6 version

See here for a functional Drupal 6-tested version.

Step 1 of 2

Put this code into your template.php inside your themes directory:
<?phpfunction phptemplate_menu_item_link($item, $link_item) {
   
/* Allow HTML if the menu text is an image tag: call l() with 7th argument set to TRUE
     * See <a href="http://api.drupal.org/api/4.7/function/l
" title="http://api.drupal.org/api/4.7/function/l
" rel="nofollow">http://api.drupal.org/api/4.7/function/l
</a>     */
   
if( strpos($item['title'], '<img') === 0) {
      return
l($item['title'], $link_item['path'], !empty($item['description']) ? array('title' => $item['description']) : array(), NULL, NULL, FALSE, TRUE);
    }
   
  return
l($item['title'], $link_item['path'], !empty($item['description']) ? array('title' => $item['description']) : array());
}
?>
Here we just look for the menu title starting with the HTML tag <img and if true call l() with the 7th argument set to TRUE. This will allow HTML inside the menu text. See http://api.drupal.org/api/4.7/function/l.

Step 2 of 2

Now just enter an image tag into the "Title" field inside the "edit menu item" form (administer > menus > (edit or add item)) like <img src="/sites/default/menu_item.gif" />

Notes

  • This code should work in Drupal 5.0 too. At least the l() function did not change from 4.7 to 5.0

Additional resources

Monday, 20 December 2010

Multisite setup using a single Drupal instance


Multisite setup using a single Drupal instance




Run multiple sites from the same code base (multi-site)


Run multiple sites from the same code base (multi-site)



Drupal multisite in subfolders






How to Setup Drupal for Multiple Sites

Drupal is a very powerful open source content management system. And one of the most attractive features from Drupal is that it will allow you to install one single Drupal code base which can serve for multiple web sites, each with its own individual configuration.
But unfortunately, the guide from Drupal office site on how to configure this feature is not clear enough, and the beginner might be lost during it. In below, we will provide you with the step by step guide to set it up:
Before we start, you should have successfully install one Drupal instance, if you still haven't, please follow the installation guide from Drupal official site to get it setup. Here, we will focus on how to add another domain to one Drupal installation.
  • Create a new database and database users for the second domain (lets call it as "domain2.com")
  • Grant full privileges to the database to the user created in the step 1)
  • Create a sub-directory in the "/sites" directory call "domain2.com", it will look like /sites/domain2.com/. Please don't include 'www' in the sub-directory.
  • Copy the /sites/default/default.settings.php to the new directory /sites/domain2.com/settings.php (don't forget to remove the 'default.' from the file name)
  • Setup the add-on domain for "domain2.com" in your web hosting account. For a shared web hosting environment, domain2.com will point to a directory like "/home/username/public_html/domain2".
  • Delete directory "/home/username/public_html/domain2"
  • Create a symlink to the main site as "/home/username/public_html/domain2", the same as what in above.
  • Launch the domain2 in browser, Drupal Installer will be launched, go through the installation process according to on-screen instructions. You will get new web site setup on the same Drupal code base.


Read more: http://www.articlesbase.com/web-hosting-articles/how-to-setup-drupal-for-multiple-sites-575160.html#ixzz18gUHSgaV 
Under Creative Commons License: Attribution

Multi-site how-tos


Multi-site how-tos


Drupal 5.1 Multi Site Configuration

Example:
1. Create dns entries for the sites ( or use hosts file for testing)
2. Create vhosts in Apache configuration file and restart Apache:
Listen 80
<VirtualHost *:80>
    DocumentRoot "C:/Program Files/xampp/htdocs"
    ServerName localhost:80
</VirtualHost>

<VirtualHost www.site1.local:80>    DocumentRoot "C:/Program Files/xampp/htdocs"
    ServerName www.site1.local:80
</VirtualHost>
<VirtualHost
www.site2.local:80>    DocumentRoot "C:/Program Files/xampp/htdocs"
    ServerName www.site2.local:80
</VirtualHost>
3. Create folder sites under drupal/sites
Note: Each site folder can have a file, tmp, modules and themes subfolders.
4. Copy settings.php from drupal/sites/default to each site folder.
5. Modify $db_url and $db_prefix in settings.php in each site folder.
For www.site1.local: Single database and db user.
$db_url = 'mysql://drupal:drupal@localhost/drupal';
$db_prefix = 'site1_';
For www.site2.local: Single database and single db user.
$db_url = 'mysql://drupal:drupal@localhost/drupal';
$db_prefix = 'site2_';
For www.site1.local: Multiple databases and single db user.
$db_url = 'mysql://drupal:drupal@localhost/site1';
$db_prefix = '';
For www.site2.local: Multiple databases and single db user.
$db_url = 'mysql://drupal:drupal@localhost/site2';
$db_prefix = '';
Note: Always use the same db user (the one that you used to install drupal for the first time) independently if you want to have a single or multiples db’s.
6. Open your web browser and point to the install.php file for each site
7. Your new sites are ready using a single code base, single db user and single or multiple db’s.

How to setup a multi-site, multi-lingual, multi-user Drupal blog

Do some basic setup

  • Setting the maintainance theme:
    • Edit settings.php and set maintenance_theme
    • Add a drupal/sites/default/theme/custom/YOURTHEME/maintenance-page.tpl.php
  • Set site information Home » Administer » Site configuration » Site information
  • Create a non-admin account for content submission, so you won't use the admin user when posting content from a non-safe place.
  • Setup Home » Administer » User management » Permissions so that users can administer contents and menu also in maintenance mode:
    • enable administer site configuration under system module for authenticated users.
  • Install and enable your preferred themes and modules
  • Specify an email address to send update notifications to, check the Settings tab in
    Home » Administer » Reports » Available updates

Remember to set also permissions in menu and node modules, such as:
  • administer menu
  • create page content
  • edit any page content
  • upload files
  • etc...

Saturday, 18 December 2010

Generate markup for drop-down menus

 http://drupal.org/node/327252

Expanding a menu tree based on node types

http://drupal.org/node/88226

If you run a Drupal site with various sections based on node types this snippet can be useful to enhance the navigational experience of your visitors.
Drupals theme_menu_tree() function offers the classes you need to highlight active menu items. But this does not work for nodes that have no menu item assigned.
To give a real world example. I run a site with a video section. In my primary links menu I have a menu item called Videos. There are several sub menu items such as most viewed, recently added, etc. When a visitor clicks on Videos the menu is expanded. Then the visitor clicks on recently added, the menu is still expanded, that is what I want. Now when the visitor actually clicks on one if the videos listed under Videos -> recently added he or she is directed to the node the video is contained in. This node has no menu item assigned and so the menu is not expanded any more. This is not what I want.
The solution for this problem is quite easy thanks to Drupals flexibility. Here we go:

Step 1

In your template.php file add the following function:
<?php// override theme_menu_item functionfunction phptemplate_menu_item($mid, $children = '', $leaf = TRUE) {
  return
_phptemplate_callback('menu_item',
  array(
'mid' => $mid, 'children' => $children, 'leaf' => $leaf));
}
?>

Step 2

Create a new file in your template directory called menu_item.tpl.php. This file contains the following lines of code:
<?php
$link
= menu_item_link($mid);
if (
arg(0) == 'node' && is_numeric(arg(1))) {
 
$node = node_load(arg(1));
}

if (
$node->type == 'video' && $mid == 158) {
 
$tree = menu_tree(158);
 
$children = "\n".'<ul class="menu">'. $tree ."\n".'</ul>';
 
// add active class to link
 
$link = str_replace('<a ', '<a class="active" ', $link);
}
$output = '<li class="'. ($leaf ? 'leaf' : ($children ? 'expanded' : 'collapsed')) .'">'.
 
$link . $children ."</li>\n";
print
$output;?>

How does this work?

Step 1 tells Drupal to override the theme_menu_item() function.
In Step 2 first we load the current menu item link and assign it to the variable $link. To get information on the node type we retrieve the current node object by passing the node id (arg(1)) to the node_load() function. Then we check whether this node is of the type video. If this returns true and the current menu id equals the id of the menu item called Videos (in my case 158) we assign the $children variable the sub menu tree of the current menu item add the active class to our link and print out the modified list item.
Now when a visitor watches a video the navigation menu is expanded and gives a clear indication that the visitor is in the video section of the web site.

Add an icon to menu links

Place this in template.php, and it'll assign a unique id to each of your menu items, allowing you to attach css (and thus icons, jquery, rollovers, etc.) to individual menu items. Very handy!
<?phpfunction phptemplate_menu_item($mid, $children = '', $leaf = TRUE) {
 
$link = menu_item_link($mid);
 
$css_id = strtolower(str_replace(' ', '_', strip_tags($link)));
  return
'<li id="' . $css_id . '" class="' . ($leaf ? 'leaf' : ($children ? 'expanded' : 'collapsed')) .'">'. $link . $children ."</li>\n";
}
?>
Then attach the usual css such as

li#my_account a{
background-image:url(../mytotallysweeticons/my_account.png);
}
Thanks goes to Nick Lewis for writing the original script - this is a slightly simpler version of that.
For users of the Framework Theme in English
Thanks to SteveJB for the following contribution.
For users of the framework theme (or any theme that by default) adds odd and even classes.
Replace (found at the bottom of the packaged template.php)

function phptemplate_menu_item($mid, $children = '', $leaf = true) {
static $count = 0;
$zebra = ($count % 2) ? 'odd' : 'even';
$count++;
return '<li class="' . ($leaf ? 'leaf' : ($children ? 'expanded' : 'collapsed')) .' ' . $zebra . '">'. menu_item_link($mid) . $children ."</li>\n";
}
with

function phptemplate_menu_item($mid, $children = '', $leaf = TRUE) {
static $count = 0;
$zebra = ($count % 2) ? 'odd' : 'even';
$count++;
  $link = menu_item_link($mid);
  $css_id = strtolower(str_replace(' ', '_', strip_tags($link)));
  return '<li id="' . $css_id . '" class="' . ($leaf ? 'leaf' : ($children ? 'expanded' : 'collapsed')) .' ' . $zebra . '">'. menu_item_link($mid) . $children ."</li>\n";
}
to keep add and even classes while giving li's their own id.
If you have a language other than English (say, Chinese), then you would have something like the following:

<li id="Chinese-characters" class="leaf">


<?php
 
function phptemplate_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {

   
$search = array(' ','.');
   
$css_id = strtolower(str_replace($search, '_', strip_tags($link)));
    return
'<li id="' . $css_id . '" class="' . ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf')) .'">'. $link . $children ."</li>\n";
  }
?>



Add odd even class to menu item


update your template.php then add preferred style to css
/* add item-odd item-even class to list */
function phptemplate_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {

static $count = 0;
$zebra = ($count % 2) ? 'odd' : 'even';
$count++;

  $class = ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf'));
  if (!empty($extra_class)) {
    $class .= ' '. $extra_class;
  }
  if ($in_active_trail) {
    $class .= ' active-trail';
  }
  $class .= ' item-'. $zebra;
  return '<li class="'. $class .'">'. $link . $menu ."</li>\n";
}

Source base installation of php, mysql and apache in ubuntu/ linux

Compile and Install a LAMP(Linux/Apache/MySQL/PHP) Server from Source In the last post, I described the method to install a LAMP ser...