Tuesday, December 27, 2011

Clear cache programmatically in Drupal 7



This will reduce the work by going to performance settings page (admin/settings/performance) & clicking "cleared cached data" by scrolling down

But make sure that this page is only accessed by administrator

For Drupal 7 is same as Drupal 6

<?php
  drupal_flush_all_caches();
  drupal_set_message('cache flushed.');
?>

Clear cache programmatically in Drupal 6


This will reduce the work by going to performance settings page (admin/settings/performance) & clicking "cleared cached data" by scrolling down

But make sure that this page is only accessed by administrator


For Drupal 6 create page with the following code:

<?php
  drupal_flush_all_caches();
  drupal_set_message('cache flushed.');
?>

Clear cache programmatically in Drupal 5



This will reduce the work by going to performance settings page (admin/settings/performance) & clicking "cleared cached data" by scrolling down

But make sure that this page is only accessed by administrator


<?php
// only allow site administrators to visit this page:
if (!user_access('administer site configuration')) {
  drupal_not_found();
}else {
  drupal_clear_css_cache();
  $tables = array('cache','cache_content','cache_filter','cache_menu','cache_page',  'cache_views');
  foreach ($tables as $table) {
    cache_clear_all('*', $table, TRUE);
  }
  drupal_set_message('Cache cleared.');
  drupal_goto();
}
?>

Monday, December 19, 2011

Get block content in drupal 6 , display block in drupal 6


In drupal 6 it was

<?php

$block = module_invoke('views', 'block', 'view', 'map-block_1');
print $block['content'];

?>

arg 1 : module name
arg 2 : hook name like block
arg 3 : $op of hook_block e.g. info, view, configure
arg 4 : id or delta of the block e.g 30, map-block_1

Get block content in drupal 7 , display block in drupal 7


If you want to view blocks in drupal 7, you have to use

<?php

$block = module_invoke('views', 'block_view', 'map-block_1');
print $block['content'];

?>

arg 1 : module name
arg 2 : hook name like block_view, block_info
arg 3 : id or delta of the block e.g 30, map-block_1

variable_set in drupal

If you are going to save a single value then:

$set = variable_set(‘name’,’value’);

If you are going to save an array then:

$array = array(‘value1’,’value2’);

$seralizedvalue = serialize($array)

$set = variable_set(‘name’,$seralizedvalue);

variable_get in drupal

$set = variable_get (‘name’,’defaultvalue’);

Variable get will retrieve the value from drupal variable table

If  ‘name’ is not there in drupal variable table this function will return the ’defaultvalue’.

This function will return serialized data.

If it return more than one value inside the serialized data then use unserialize() function to convert the serialized data into array.

If it contains only one value then you can fetch it directly i.e. the returned value will get saved to $set directly.

Monday, December 12, 2011

Remove last character of a string in javascript


//Input : "Kumar,Raj,Ram,"
//Removes the last charecter comma from the string

var ins  =  'Kumar,Raj,Ram,';
ins = ins.substring(0, ins.length-1);
alert(ins);

//Output = "Kumar,Raj,Ram"

in_array in javascript


 /*
   *PHP in_array function  in  javascript
   */
   function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array
    //
    // *     example 1: in_array('Raj', ['Kumar', 'Tom', 'Raj']);
    // *     returns 1: true
    // *     example 2: in_array('Hari', {0: 'Kathir', Hari: 'Passat', 1: 'Raj'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
     var key = '',
        strict = !! argStrict;

     if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
     } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
     }

     return false;
   }

Wednesday, December 7, 2011

Convert xml string into an array using php

<?php

   $string = <<<XML
   <?xml version='1.0'?>
   <document>
   <title>Forty What?</title> 
   <from>Joe</from>
   <to>Jane</to>
   <body>
   I know that's the answer -- but what's the question?
   </body>
   </document>
   XML;

   $xml = simplexml_load_string($string);

   print_r($xml);

?>

Output:

SimpleXMLElement Object ( [title] => Forty What? [from] => Joe [to] => Jane [body] => I know that's the answer -- but what's the question? )

Select & unselect all check box using jquery or Check & uncheck all check box using jquery

$(document).ready(function() {

$("#checkall").click(function()
{
var chk_sts = this.checked;
$('input:checkbox[name=checkboxname]').each(function(i)
{
this.checked = chk_sts;
});
});

});

* Include latest jquery js file
* "#checkall" is the id to check box where you want a click to check all other check boxes

Friday, December 2, 2011

Get row count in Drupal 6 , Get row count in drupal 6

The below function has to be written after the execution of query using db_query();

db_affected_rows()

function will return the number of rows the query return;

Thursday, December 1, 2011

Get checked check box value in jquery

IF you have only one check box group in the form

$('input:checkbox:checked').each(function(i){
    alert($(this).val());
});


If you have many check box group you have to mention the group name

$('input:checkbox[name=checkboxname]:checked').each(function(i){
    alert($(this).val());
});

Monday, November 28, 2011

Change to hook_nodeapi in drupal 7

hook_nodeapi() in Drupal 6 became (see Node API page) hook_node_delete(), hook_node_insert(), hook_node_load(), hook_node_prepare(), hook_node_prepare_translation(), hook_node_search_result(), hook_node_presave(), hook_node_update(), hook_node_update_index(), hook_node_validate(), and hook_node_view() in Drupal 7.

Example in Drupal 6 :

/**
* Implements hook_nodeapi().
*/
function hook_nodeapi(&$node, $op, $teaser, $page) {
switch ($op) {
case 'load':
// Load a book.
}
}

Example in Drupal 7 :

/**
* Implements hook_node_load().
*/
function hook_node_load($nodes, $types) {
// Load a book.
}


/**
* Implements hook_node_update().
*/

function hook_node_update($node) {
db_update('mytable')
->fields(array('extra' => $node->extra))
->condition('nid', $node->nid)
->execute();
}

/**
* Implements hook_node_insert().
*/

function hook_node_insert($node) {
db_insert('mytable')
->fields(array(
'nid' => $node->nid,
'extra' => $node->extra,
))
->execute();
}

Thursday, November 24, 2011

Check whether text contain html tags using php

There are two ways you can do it, one is using a regular expression and the other is comparing strings.

First the regular expression approach:

if (preg_match("/([\<])([^\>]{1,})*([\>])/i", $string)) {
echo "string contains html";
}

Second a comparing string approach:

if(strlen($string) != strlen(strip_tags($string)){
echo "string contains HTML";
}

Wednesday, November 23, 2011

Usage of Like query in drupal6

You have to out two percentage between %s

$sql = "SELECT title FROM node WHERE type='%%%s' AND title LIKE '%%%S%%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));

Export mysql schema alone in command line

MysqlExport Only schema :

Go to mysql bin directory in command prompt
mysqldump --no-data --tables –u username –p dbname --routines --triggers > c:/file.sql
Press enter
Enter Password:
Enter your password
You are done with it

Friday, October 7, 2011

Changing Theme with Init Hook

If you need to actually change a theme, you need to write the following in a module's init hook:

function yourmodule_init() {
global $custom_theme, $theme;

//... some logic ...

$theme = null;
$custom_theme = 'chameleon'; // 'chameleon' being the theme you want to set

}

Jquery Events not working on ajax loaded content

Use the click function for the ajax loaded content as below

$(‘.classname’).live(“click”,function(){
});

Thursday, September 22, 2011

How to instantiate a PHP class with dynamic parameters

Two Best Solutions :

function create_instance($class, $params) {

return call_user_func_array(
array(new ReflectionClass($class), 'newInstance'),
$params
);
}

or

function create_instance($class, $params) {

$reflection_class = new ReflectionClass($class);
return $reflection_class->newInstanceArgs($params);
}

Custom Theme the maintenance ("Site Offline") page

Step 1: Override the maintenance page template

Copy your main page.tpl.php and rename it to maintenance-page.tpl.php or copy the template located in modules/system/maintenance-page.tpl.php to your theme

Step 2: Indicate in your settings.php file

specify the theme name in which u have put the maintenance-page.tpl.php in step 1

this has to be in settings.php
<?php
$conf['maintenance_theme'] = 'themeName';
?>

Step 3: Create the maintenance offline page in the case of database failure

event warnings about the database connection from appearing, copy your page.tpl.php file and rename it maintenance-page-offline.tpl.php. Change the $content variable with your custom message. Note, this template file is a template suggestion based on maintenance-page.tpl.php so they both need to exist in the same folder.

At the top of maintenance-page-offline.tpl.php, you might also want to set the following variables detailed in step 4.

Step 4: Hard code site settings

In this mode, your database is inaccessible, therefore some key settings about your site are not available. If you want this page to use the same theme and other settings that the site would normally use, you must replicate those settings by using hard-coded values.

<?php
$head_title = 'mysite.com :: Site-offline';
$logo = 'sites/all/files/customLogo.png';

// If your theme is set to display the site name, uncomment this line and replace the value:
// $site_name = 'Your Site Name';

// If your theme is set to *not* display the site name, uncomment this line:
unset($site_name);

// If your theme is set to display the site slogan, uncomment this line and replace the value:
$site_slogan = 'My Site Slogan';

// If your theme is set to *not* display the site slogan, uncomment this line:
// unset($site_slogan);

// Main message. Note HTML markup.
$content = 'The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.If you are the maintainer of this site, please check your database settings.';

?>

Overriding other theme functions

If you want to override a theme function not included in the basic list (block, box, comment, node, page), you need to tell PHPTemplate about it.
To do this, you need to create a template.php file in your theme's directory. This file must start with a PHP opening tag <?php but the close tag is not needed and it is recommended that you omit it. Also included in the file are stubs for the theme overrides. These stubs instruct the engine what template file to use and which variables to pass to it.
First, you need to locate the appropriate theme function to override. You can find a list of these in the API documentation. We will use theme_item_list() as an example.
The function definition for theme_item_list() looks like this:
<?php
function theme_item_list($items = array(), $title = NULL) {
$output = '<div class="item-list">';
if (isset($title)) {
$output .= '<h3>'. $title .'</h3>';
}

?>
Now you need to place a stub in your theme's template.php, like this:
<?php
/**
* Catch the theme_item_list function, and redirect through the template api
*/
function phptemplate_item_list($items = array(), $title = NULL) {
// Pass to phptemplate, including translating the parameters to an associative array.
// The element names are the names that the variables
// will be assigned within your template.
return _phptemplate_callback('item_list', array('items' => $items, 'title' => $title));
}

?>
We replaced the word theme in the function name with phptemplate and used a call to _phptemplate_callback() to pass the parameters ($items and $title) to PHPTemplate.
Now, you can create a file item_list.tpl.php file in your theme's directory, which will be used to theme item lists. Start by putting in the code from the original theme_item_list(). Do not wrap this code into a function, write inline, e.g.
<?php
$output = '<div class="item-list">';
if (isset($title)) {
$output .= '<h3>'. $title .'</h3>';
}

?>

Making additional variables available to your templates

Example 1:
<?php
function _phptemplate_variables($hook, $vars) {
switch($hook) {
case 'comment' :
$vars['newvar'] = 'new variable';
$vars['title'] = 'new title';
break;
}
return $vars;
}

?>


Example 2:
<?php
function _phptemplate_variables($hook, $vars) {
switch ($hook) {
case 'page':
if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
$vars['content_is_node'] = TRUE;
}
break;
}
return $vars;
}
?>

Theming blocks individually, by region, or by module

Designers can create multiple tpl.php files for blocks based on the specific block, the module that created the block, or the region that the block appears in.
Template files are searched in the following order:
block-[module]-[delta].tpl.php
block-[module].tpl.php
block-[region].tpl.php
block.tpl.php
For example, the user login block has a delta of '0'. If you put it in the left sidebar, when it's rendered, PHPTemplate will search for the following templates in descending order:
block-user-0.tpl.php
block-user.tpl.php
block-left.tpl.php
block.tpl.php
You can find the block's module and delta by looking at the html source of a page: each block's main DIV has the following classes and IDs:
<div class="block block-{module}" id="block-{module}-{delta}">
Note that custom blocks created in the admin UI count as coming block.module, so their template is 'block-block-[delta]'.

Import & export database in mysql using command line

MysqlExport :

Go to bin directory
mysqldump –u expuser –p dbname --routines > c:/file.sql
Press enter
Enter Password:
Enter your password
You are done with it

MysqlImport :

Go to bin directory
mysql –uexpuser –p dbname < c:/dile.sql
Press Enter
Enter Password: will appear
Enter your password
You are done with it

Another way is:
Connect with mysql in commond prompt
mysql>Create database dbname;
mysql>User dbname;
mysql>Source file.sql; ExpertusONE_db.sql

Adding Language Icons in drupal

In Drupal, language flags can be easily included in the language switcher with the Language Icons modulehttp://drupal.org/project/languageicons.











Go to http://drupal.org/project/languageicons and download the module and install in your sites/all/modules directory.
Navigate to the module admisistration page in your website, /admin/build/modules, and enable the "Language Icons" module listed under the "Multilanguage" section.
Then save the configuration and that's it, you should now have flags in your language switcher.

Tuesday, June 21, 2011

Example of drupal_write_record or Example of drupal write record

Insert a value into database :

$transition = array(
'sid' => $form_state['values']['new_transition_from'],
'target_sid' => $form_state['values']['new_transition_to'],
'roles' => $tabroles,
);
drupal_write_record('workflow_transitions', $transition);

Update a value into database :

$transition = array(
'sid' => $form_state['values']['new_transition_from'],
'target_sid' => $form_state['values']['new_transition_to'],
'roles' => $tabroles,
'tid' => $tid
);

drupal_write_record('workflow_transitions', $transition, 'tid');

In Update primary key is tid

Usage of drupal_add_js()

<?php
// This will add a JS file to your head (specifically the $scripts variable in page.tpl.php)
drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

// This add inline JS to the head of the document
drupal_add_js('alert("Hello!")', 'inline');

// This will add variables in the Drupal.settings object
drupal_add_js(array('my_module' => array('my_setting' => 'this_value')), 'setting');
?>

Including js file in drupal

Adding JavaScript from within a module
<?php
drupal_add_js(drupal_get_path('module', 'mymodule') .'/my_js_file.js');
?>

Adding JavaScript from within a theme
<?php
drupal_add_js(drupal_get_path('theme', 'mytheme') .'/my_js_file.js', 'theme');
?>

Using the theme's .info file (Drupal 6)
name = My theme
description = Theme developed by me.
core = 6.x
engine = phptemplate
version = 6.x-1.0
;
scripts[] = my_script.js

Create a file & provide download option for that file

$myFile = "path_to_dir/test.(EXTENSION)EG jpg,js";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Contents to display";
fwrite($fh, $stringData);
fclose($fh);
if (file_exists($myFile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($myFile));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($myFile));
ob_clean();
flush();
readfile($myFile);
exit;
}

Example with l of in drupal

l('TITLE','node/33');

Output:
<a href="/?q=node/33">TITLE</a>

l('TITLE','node/33',array('attributes'=>array('target'=>"_blank")));

Output :
<a href="/?q=node/33" target="_blank">TITLE</a>

l('TITLE','node/33',array('query'=>array('disp'=>4),'attributes'=>array
('target'=>"_blank")));

Output :
<a href="/?q=node/33&disp=4" target="_blank">TITLE</a>

l('TITLE','node/33',array('attributes'=>array('target'=>"_blank")),'fragment'=>'comment-
1');

Output :
<a href="/?q=node/33#comment-1" target="_blank">TITLE</a>

l('TITLE','node/33',array('query'=>array('disp'=>4),'attributes'=>array
('target'=>"_blank")),'fragment'=>'comment-1');

Output :
<a href="/?q=node/33&disp=4#comment-1" target="_blank">TITLE</a>

Create translation js file based on the po file content imported in database

//Pass the language code.
function custom_translation_create_js($language) {
// Get information about the locale.
$languages = language_list();
$language = $languages[$language];

// Construct the array for JavaScript translations.
// We sort on plural so that we have all plural forms before singular forms.
$result = db_query("SELECT s.lid, s.source, t.plid, t.plural, t.translation FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE t.language = '%s' ORDER BY t.plural DESC", $language->language);

$translations = $plurals = array();
while ($data = db_fetch_object($result)) {
// Only add this to the translations array when there is actually a translation.
if (!empty($data->translation)) {
if ($data->plural) {
// When the translation is a plural form, first add it to another array and
// wait for the singular (parent) translation.
if (!isset($plurals[$data->plid])) {
$plurals[$data->plid] = array($data->plural => $data->translation);
}
else {
$plurals[$data->plid] = array($data->plural => $data->translation);
}
}
elseif (isset($plurals[$data->lid])) {
// There are plural translations for this translation, so get them from
// the plurals array and add them to the final translations array.
$translations[$data->source] = array($data->plural => $data->translation) + $plurals[$data->lid];
unset($plurals[$data->lid]);
}
else {
// There are no plural forms for this translation, so just add it to
// the translations array.
$translations[$data->source] = $data->translation;
}
}
}

// Only operate when there are translations.
if (!empty($translations)) {
// Construct the JavaScript file.
$data = "Drupal.locale = { ";

if (!empty($language->formula)) {
$data .= "'pluralFormula': function(\$n) { return Number({$language->formula}); }, ";
}

$data .= "'strings': ". drupal_to_js($translations) ." };";

$data_hash = md5($data);

// Construct the directory where JS translation files are stored.
// There is (on purpose) no front end to edit that variable.
$dir = file_create_path(variable_get('locale_js_directory', 'languages'));
// Only create a new file if the content has changed.
if ($language->javascript != $data_hash) {
if (!empty($language->javascript)) {
// We are recreating the new file, so delete the old one.
file_delete(file_create_path($dir .'/'. $language->language .'_'. $language->javascript .'.js'));
$language->javascript = '';
}
else {
// The directory might not exist when there has not been a translation
// file before, so create it.
file_check_directory($dir, TRUE);
}
$str = "trans";
// The file name of the new JavaScript translation file.
$dest = $dir .'/'. $language->language .'_'. $str .'.js';
$path = file_save_data($data, $dest);

db_query("UPDATE {languages} SET javascript = '%s' WHERE language = '%s'", $path ? $data_hash : '', $language->language);

// Only report updated or creation when there is actually a file created.
if ($path) {
// There has already been a translation file before.
if (!empty($language->javascript)) {
watchdog('locale', t('Updated JavaScript translation file for the language %language.', array('%language' => t($language->name))));
}
else {
watchdog('locale', t('Created JavaScript translation file for the language %language.', array('%language' => t($language->name))));
}
}
else {
watchdog('locale', t('An error occured during creation of the JavaScript translation file for the language %language.', array('%language' => t($language->name))));
}
}
}

// There are no strings for JavaScript translation. However, if there is a file,
// delete it and reset the database.
elseif (!empty($language->javascript)) {
// Delete the old JavaScript file
file_delete(file_create_path(variable_get('locale_js_directory', 'languages') .'/'. $language->language .'_'. $language->javascript .'.js'));
db_query("UPDATE {languages} SET javascript = '' WHERE language = '%s'", $language->language);
watchdog('locale', t('Deleted JavaScript translation file for the locale %language.', array('%language' => t($language->name))));
}
}

Language translation for Drupal JavaScript files.

1. Make sure that you have entered Drupal.t () function before all the text.
2. You have to create a js file (fr-trans.js) like below u for corresponding language
Drupal.locale = {‘strings’: {"Certification":"Certification","Required":"Requis"}};
In my example I have given for French language.
3. Include the js file based on user language

Language translation in Drupal Based on user language or based on website

1. Make sure that you have entered t() function before all the text.
2. Install the locale module.
3. In admin settings to Languages Link add languages which you need.
4. Click on configure you can see language negotiation you have to select”
Path prefix with language fallback. "(You have to do this if you want language translation
based on user selected language in his my account page) Or In admin setting languages Click the default language for the webpage to change page to corresponding language(This will change the language of webpage)
5. Download the default po file provided by drupal from this link
http://localize.drupal.org/ for testing purpose. (Note: You need to create a po file
based on your content of you website )
6. Go to Translate interface link in site building
7. Click on the import link & select the language & import the selected language po file
8. Check for a particular user by changing his language

Saturday, May 7, 2011

Put a pipe symbol in between primary link

1.Pu this code in the template.php file of your theme folder
2.Check the class of primary links in the page.tpl or page-front.tpl matches with class condition check indie this function if this function doesn't work

function youthemename_links($links, $attributes = array('class' => 'links')) {
$output = '';
// Change the way primary links are rendered
if($attributes['class'] == 'links primary-links') {
$linklist = array();
foreach ((array)$links as $key => $link) {
$linklist[] = l($link['title'], $link['href'], $link);
}
// Return the links joined by a '|' character
return join(' | ', $linklist);
}
// Normal theming continued below:

if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';

$num_links = count($links);
$i = 1;

foreach ($links as $key => $link) {
$class = $key;

// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ' first';
}
if ($i == $num_links) {
$class .= ' last';
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '' && drupal_is_front_page()))) {
$class .= ' active';
}
$output .= '<li class="'. $class .'">';

if (isset($link['href'])) {
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = '';
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
}

$i++;
$output .= "</li>\n";
}

$output .= '</ul>';
}

return $output;
}

Remove formating text & split summary cursor button in drupal

You should put this is code inside hook_alter of any your custom module
-----------------------------------------------------------------------------------------------------------

$form['body_field']['format'] = array();
$form['body_field']['teaser_include'] = array('#type' => 'value','#value' => TRUE,);

Friday, April 22, 2011

Dynamically display the title of page

<?php

 $items['tespage'] = array(
  'title callback' => 'custommodule_get_title',
  'title arguments' => array(1),
  'type' => MENU_CALLBACK,
  'page arguments' => array(5),
  'access arguments' => array('administer customworkflow'),
 );

/**
*Function to display the title dymnamically
*Parameters passed
*@param $arg
* Passing the id to get the custom name
*/
 function custommodule_get_title($arg){
  $arg = ($arg)?$arg:arg(1);
//Based on argument do the operation
  $name = custom_get_name($arg);
  return "Edit ".drupal_ucfirst($name);
 }

?>

Add a class to body tag for a particular menu

<?php
/**
* Override or insert PHPTemplate variables into the templates.
*/
//In template.php file
  function phptemplate_preprocess_page(&$vars) {
    if(arg(0) == "node" && arg(1) == 2){
      $vars['body_classes'] = $vars['body_classes']." testing";
    }
    return $vars;
  }
?>

Change or customize the system theme for a menu callback

//Put this code to the menu callback

<?php
  global $custom_theme;
  $custom_theme="acquia_marina";
?>

Example of drupal_render usage

<?php

//DRUPAL RENDER USAGE
$form['add_wf_mapping'] = array(
 '#type' => 'button',
 '#id'=>'edit-add-wf-mapping',
 '#name'=>'edit-add-wf-mapping',
 '#attributes' => array('style'=>'margin:0px'),
 '#value' => t('Map Workflow')
);
$output .=drupal_render($form['add_wf_mapping']);

echo $output;

Output  the button

?>

Thursday, April 21, 2011

View unpublished content by an moderator or content editor(custom role created)

1.Create an custom module view_unpublished
2.Place this code in it

<?php

/**
* Implementation of hook_perm().
*/
function view_unpublished_perm() {
$perms = array('view all unpublished content');
foreach (node_get_types() as $type => $name) {
$perms[] = 'view unpublished ' . $type . ' content';
}
return $perms;
}

/**
* Implementation of hook_menu_alter().
*
* Modifies the path node/nid to use our access callback.
*/
function view_unpublished_menu_alter(&$items) {

$old_access_callback = $items['node/%node']['access callback'];
$items['node/%node']['access callback'] = '_view_unpublished_node_access';
$items['node/%node']['access arguments'] = array(1, $old_access_callback);
}

/**
* Returns true if the user has 'view all unpublished content' or if
* they have the permission corresponding to the node's content type.
*/
function _view_unpublished_node_access($node, $old_access_callback = "node_access") {
// Only check permissions on nodes that are unpublished.
if ($node->status == 0) {
if (user_access('view all unpublished content')) {
return TRUE;
}

if (user_access('view unpublished ' . $node->type . ' content')) {
return TRUE;
}
}
// If none of the above conditions were satisfied, then use the normal callback.
return $old_access_callback('view', $node);
}


?>

Wednesday, April 20, 2011

change template files based on an cck or an url

Customize templates based on CCK or URL

Drupal6
<?php
function themename_preprocess_page(&$variables) {
//Templete file for each content type
if ($variables['node']->type != "") {
$variables['template_files'][] = "page-node-" . $variables['node']->type;
}
//Seperate Templete file for the path node/3
if ((arg(0) == 'node') && is_numeric(arg(1)) && (arg(2) == NULL) && arg(1)==3) {
$variables['template_files'][] = "page-test";
}
}
?>

Drupal 7
<?php

function themeName_preprocess_page(&$vars, $hook) {
if (isset($vars['node'])) {
// If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
$vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
}
}
?>

Saturday, March 26, 2011

Send mail in Drupal 7 & Drupal 6

<?php

function example_notify($accounts) {
$language = language_default();
$params = array();
$from ="admin@testsite.com"
('example', 'notice','kumarit84@gmail.com',$language ,$params,$from);
}

function example_mail($key, &$message, $params) {
$data['user'] = $params['account'];
$options['language'] = $message['language'];
user_mail_tokens($variables, $data, $options);
switch($key) {
case 'notice':
$langcode = $message['language']->language;
$message['subject'] = t('Notification from !site', $variables, array('langcode' => $langcode));
// Make emails HTML friendly
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
$message['body'][] = t("Dear !username\n\nThere is new content available on the site.", $variables, array('langcode' => $langcode));
break;
}
}

?>

Create cck using custom module

1. Create an table with for fields other than title & body.Here i have created an table employee with three fields vid,nid,age.

2.Create an custom module with module folder name employee.

3.Copy the above code & paste in your module file.

4.Go through the code once.

<?php
/**
* Implementation of hook_node_info().
*/
function employee_node_info() {
return array(
'employee' => array(
'name' => t('Employee'),
'module' => 'employee',
'description' => "Create an Employee",
)
);
}

/**
* Implementation of hook_perm().
*/
function employee_perm() {
return array('create employee', 'edit own employee');
}

/**
* Implementation of hook_access().
*/
function employee_access($op, $node) {
global $user;

if ($op == 'create') {
// Only users with permission to do so may create this node type.
return user_access('create employee');
}

// Users who create a node may edit or delete it later, assuming they have the
// necessary permissions.
if ($op == 'update' || $op == 'delete') {
if (user_access('edit own employee') && ($user->uid == $node->uid)) {
return TRUE;
}
}
}

/**
* Implementation of hook_form().
*/
function employee_form(&$node, $form_state) {
$type = node_get_types('type', $node);

// We need to define form elements for the node's title and body.
$form['title'] = array(
'#type' => 'textfield',
'#title' => check_plain($type->title_label),
'#required' => TRUE,
'#default_value' => $node->title,
'#weight' => -5
);

$form['age'] = array(
'#type' => 'textfield',
'#title' => 'Age',
'#required' => TRUE,
'#default_value' => $node->age,
'#weight' => -4
);
// We want the body and filter elements to be adjacent. We could try doing
// this by setting their weights, but another module might add elements to the
// form with the same weights and end up between ours. By putting them into a
// sub-array together, we're able force them to be rendered together.
$form['body_filter']['body'] = array(
'#type' => 'textarea',
'#title' => check_plain($type->body_label),
'#default_value' => $node->body,
'#required' => FALSE
);
$form['body_filter']['filter'] = filter_form($node->format);

// NOTE in node_example there is some addition code here not needed for this simple node-type

return $form;
}

/**
*Load the values of custom fields in CCK
*/
function employee_load($node) {
$additions = db_fetch_object(db_query('SELECT age FROM {employee} WHERE vid = %d', $node->vid));
return $additions;
}

/**
*Insert the values of custom field of CCK into an custom table created
*/
function employee_insert($node) {
db_query("INSERT INTO {employee} (vid, nid, age) VALUES (%d, %d, '%d')", $node->vid, $node->nid, $node->age);
}

/**
*Delete the node from the custom table
*/
function employee_delete($node) {
// Notice that we're matching all revision, by using the node's nid.
db_query('DELETE FROM {employee} WHERE nid = %d', $node->nid);
}


/**
*Update the node into the custom table
*/
function employee_update($node) {
// if this is a new node or we're adding a new revision,
if ($node->revision) {
employee_insert($node);
}
else {
db_query("UPDATE {employee} SET age = %d WHERE vid = %d", $node->age, $node->vid);
}
}


/**
* Implementation of hook_help().
*/
function employee_help($path, $arg) {
switch ($path) {
case 'admin/help/employee':
return '

' . t('Help Custom CCK') . '

';
break;
}
}

?>

Drupal mail with attachment

* You have to set the smtp username ,password,host in the admin settings page

<?php

/*
* This function send mail with attachement
*
*/
function drupal_mail_wrapper_attachment($mailkey, $to, $subject, $body, $from, $header,$attachment="") {
$mail = new phpmailer(); //Create a new phpmailer object.
$username = variable_get('smtp_username', '');
$password = variable_get('smtp_password', '');

//Set the default name emails should be from. If value is not defined in settings use site_name.
if (variable_get('smtp_fromname', '') != ''){
$from_name = variable_get('smtp_fromname', '');
}
else{
$from_name = variable_get('site_name', '');
}

//If from email address is blank use smtp_from config option
if ($from == '' && variable_get('smtp_from', '') != ''){
$from = variable_get('smtp_from', '');
}

//Decide whether to use SMTP Authorization. Do so if username and password are given.
if ($username != '' and $password != '') {
$auth = TRUE;
} else {
$auth = FALSE;
}


//Take care of the email headers.
foreach ($header as $key => $value) {
//watchdog('error', 'Key: ' . $key . ' Value: ' . $value);
if (strtolower($key) == 'from') {
if ($from == NULL or $from == '') {
$from = $value; //If a from value was already given then set based on header.
}
}
else if (strtolower($key) == 'content-type' && strpos(strtolower($value),'text/html') !== FALSE) {
$mail->IsHTML(TRUE);
}
else if (strtolower($key) == 'content-type' && strpos(strtolower($value), 'multipart/mixed') !== FALSE) {
//$body passed to smtp should already be formatted. add multipart header and tell phpmailer to leave it alone
$mail->AddCustomHeader($key . ": " . $value);
$mail->message_type = "pre";
}
else if (strtolower($key) == 'reply-to') {
$mail->AddReplyTo = $value;
}
else if (strtolower($key) == 'return-path') {
if (trim($value) != '') {
$mail->Sender = $value;
}
}
else if (strtolower($key) == 'content-transfer-encoding') {
$mail->Encoding = $value;
}
else if (strtolower($key) == 'mime-version') {
// just ommit MIME-Version it since it will be set by PHP-Mailer
}
else if (strtolower($key) == 'bcc') {
$bccrecipients = split(",", $value);
foreach ($bccrecipients as $bccrecipient) {
if ( strpos($bccrecipient, '<') !== false ) {
$bccparts = explode(" <", $bccrecipient);

$bccname = $bccparts[0];
$bccaddr = rtrim($bccparts[1], ">");
}
else {
$bccname = "";
$bccaddr = $bccrecipient;
}
$mail->AddBCC($bccaddr, $bccname);
}
}
else { //Else the header key is not special, just add it.
$mail->AddCustomHeader($key . ": " . $value); //Add header line.
}
}

//If no from address has been set than use a default.
if ($from == '' or $from == NULL){
$from = variable_get('site_mail', 'test@example.com'); //If no from can be found use site_mail variable.
}

//Set the correct protocol prefix to append to the smtp host.
switch(variable_get('smtp_protocol', 'standard')){
case "ssl":
$mail->Protocol = 'ssl://';
break;
case "tls":
$mail->Protocol = 'tls://';
break;
case "standard":
$mail->Protocol = '';
}

$mail->Host = variable_get('smtp_host', '') . ';' . variable_get('smtp_hostbackup', '');
$mail->Port = variable_get('smtp_port', '25');
$mail->Mailer = "smtp";
$mail->SMTPAuth = $auth;
$mail->Username = $username;
$mail->Password = $password;
$mail->CharSet = 'utf-8';

$mail->From = $from;
$mail->FromName = $from_name;

$torecipients = split(",", $to);
foreach ($torecipients as $torecipient) {
if (strpos($torecipient, '<') !== false) {
$toparts = explode(" <", $torecipient);
$toname = $toparts[0];
$toaddr = rtrim($toparts[1], ">");
}
else {
$toname = "";
$toaddr = $torecipient;
}
$mail->AddAddress($toaddr, $toname);
}

$mail->Subject = $subject;
$mail->Body = $body;
if(count($attachment)) {
foreach ($attachment as $attachments) {
//$target_path_pdf = file_directory_path().'/bill/new/meha.pdf';
$mail->AddAttachment($attachments); // attachment
}
}
watchdog('smtp', "Sending mail to: $to");
//Try to send email, if it fails set watchdog entry.
if(!$mail->Send()) {
watchdog("smtp", "Error sending email: '". $mail->ErrorInfo ."' From: '$from' To: '$to'", WATCHDOG_ERROR);
return false;
}
$mail->SmtpClose();
return true;
}

?>