Monday, January 31, 2011

What is the difference between Body.OnLoad and jQuery document.ready() Event?

The main differences between the two are:
Body.Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document.ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded. Hence, the functions in jQuery's ready event will get executed once the HTML structure is loaded without waiting for the resources.
We can have multiple document.ready() in a page but Body.Onload() event cannot.

Additional submit button on node forms.

Sometimes you are asked to add a second submit button above each node form.
This can be easily done with a few lines of code:

secondsubmit.info
; $Id$
name = "Second submit"
description = "Second submit button on node forms."
core = "6.x"
secondsubmit.module
// $Id$

/**
* @file
* Module definition for secondsubmit.
*/

/**
* Implement hook_form_alter().
*/
function secondsubmit_form_alter(&$form, $form_state, $form_id) {
// Add a second submit button to node forms.
if ($form['#node'] && ($form_id == $form['#node']->type . '_node_form')) {
$form['secondsubmit'] = array(
'#type' => 'submit',
'#value' => t('Save & continue'),
'#weight' => -10,
'#validate' => array('node_form_validate'),
// Use default and an additional submit handler.
'#submit' => array('node_form_submit', 'additional_node_form_submit'),
);
}
}

/**
* Implement of additional form submit
*/
function additional_node_form_submit($form, &$form_state) {
// ...
}
?>

Grouping an array based on value of the array

this example Groups the array based on color

function groupbyfirst($array)
{

foreach ($array as $row)

{

$firstkeys = array_keys($row);

$firstkey = $firstkeys[0];

$firstkey = strtolower($row[$firstkey]);

$tol = $firstkey;

$newarray[$tol][] = $row;

}

return $newarray;

}



$array =

Array(

0 => Array('color' => 'red','name' => 'apple', 'quantity' => '3'),

1 => Array('color' => 'green','name' => 'pear', 'quantity' => '2'),

2 => Array('color' => 'yellow','name' => 'corn', 'quantity' => '3'),

3 => Array('color' => 'blue','name' => 'grape', 'quantity' => '4'),

4 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '13'),

5 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '15'),

);



$output = groupbyfirst($array);

echo "
";

print_r($output);

echo "
";

Cascading style order

1.inline style.
2.embedded style.
3.external style
4. @import method.

Saturday, January 22, 2011

Uploading files in Drupal 6

function myform() {
$form = array();
// If this #attribute is not present, upload will fail on submit
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['file_upload'] = array(
'#title' => t('Upload file'),
'#type' => 'file',
);
$form['submit_upload'] = array(
'#type' => 'submit',
'#value' => 'Submit'
);
return $form;
}

function myform_submit($form, &$form_state) {
$validators = array();
$dest = 'upload_directory';
$file = file_save_upload('file_upload', $validators, $dest);
//$file will be 0 if the upload doesn't exist, or the $dest directory
//isn't writable
if ($file != 0) {
$dest_path = 'upload_directory/file';
$result = file_copy($file, $dest_path, FILE_EXISTS_RENAME);
if ($result == 1) {
//Success, $file object will contain a different (renamed)
//filename and filepath if the destination existed
}
else {
//Failure
}
}
else {
form_set_error('myform', t("Failed to save the file."));
}
}

Wednesday, January 19, 2011

Cannot Create width for an inline div

You cannot create width for an inline div. to Create an width for an inline div you have change

From
display:inline
TO
display:inline-block;

this css will allow u to create width for the inline div

Wednesday, January 12, 2011

Create new users programatically in drupal


//fill out these values for the user you want to add
$new_users[0] = array(
'name' => 'login_name_here',
'pass' => 'password_here',
'mail' => 'email_here',
'access' => '0',
'status' => 0,
);

//fill out this user for the next user you wish to add. To add more than two, cut and paste this block, making sure to add one number to the variable that immediately follows, $new_users. For instance, the next would be $new_users[2] = arra.... you get the picture.
$new_users[1] = array(
'name' => '2nd-login_name_here',
'pass' => '2nd-password_here',
'mail' => '2nd-email_here',
'access' => '0',
'status' => 0,
);


foreach( $new_users as $key => $value ){
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $new_users[$key]['name'] );
$data = db_result( $result );
print_r($data);
if ( !$data ) {
user_save( NULL, $new_users[$key], NULL );

}
}

?>

truncate_utf8() is used as a substring function in drupal

In Drupal 4.7 – 6
truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE)

In Drupal 7
truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE,$min_wordsafe_length = 1)


Truncate a UTF-8-encoded string safely to a number of characters.
Parameters

$string The string to truncate.

$len An upper limit on the returned string length.

$wordsafe Flag to truncate at last space within the upper limit. Defaults to FALSE.

$dots Flag to add trailing dots. Defaults to FALSE.
Return value

The truncated string

Embed Drupal Views Using PHP

When theming Drupal and wanting to output a view there are occasions where using a view display (e.g. a page, or a block - perhaps placed within a custom region ;-) ), or using Views Attach will not suffice.

Instead, you can embed a view using the following PHP snippet:

(NOTE: you'll need to have the core PHP input filter enabled if embedding in a node body)


$view = views_get_view('VIEWNAME');

print $view->preview('default');

?>

or, if you need to use an argument with the view:


$args = array(ARGUMENTS);

$view = views_get_view('VIEWNAME');

print $view->preview('default', $args);

?>

Wednesday, January 5, 2011

New hooks in drupal 7

New hooks: hook_modules_installed, hook_modules_enabled, hook_modules_disabled, and hook_modules_uninstalled

1.Four new hooks are provided so that other modules can react to modules' status changes. Each hook is passed an array of module short-names, i.e. array('blog', 'blogapi'). Note, these hooks should NOT be used by a module for its own installation or uninstallation; hook_install or hook_uninstall should be used. See the documentation for each hook for more information.

hook_modules_installed
hook_modules_enabled
hook_modules_disabled
hook_modules_uninstalled

New taxonomy hooks for term and vocabulary
New hooks are provided for taxonomy terms to allow modules to add information to the term object.

hook_taxonomy_term_load
hook_taxonomy_term_presave
hook_taxonomy_term_insert
hook_taxonomy_term_update
hook_taxonomy_term_delete
hook_taxonomy_vocabulary_load
hook_taxonomy_vocabulary_presave
hook_taxonomy_vocabulary_insert
hook_taxonomy_vocabulary_update
hook_taxonomy_vocabulary_delete

2.New hook: hook_username_alter()

3.New hooks: hook_admin_paths() and hook_admin_paths_alter()

New hooks are provided for indicating which paths on a Drupal site are associated with administrative actions. Modules should implement these hooks to specify any paths at which administration-related activities might be expected to occur. Note that pages which can be used interchangeably for both administrative and non-administrative purposes (for example, content creation pages) should be labeled administrative for the purposes of this hook.

It is not necessary for modules to use this hook to define administrative paths that live underneath the traditional admin/* location, since Drupal core already implements the hook to define these paths as administrative by default.

Other modules may use this information in a variety of ways - for example, to display administrative pages in a modal overlay, or in a different theme; the function path_is_admin() is provided for this purpose

Changes in hook of Drupal 7

Changes in hooks of Drupal7

1.hook_nodeapi, hook_node_type, hook_user, and hook_block removed and replaced with families of related functions

In Drupal 7, several hooks that previously allowed modules to do a group of related operations, with a $op argument, were split into individual hooks for each operation. Gábor posted a note in the developer mailing list about this if you'd like to read more about it.

The hooks that were changed in this way:

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().

hook_node_type() in Drupal 6 became (see Node API page) hook_node_type_delete(), hook_node_type_insert(), andhook_node_type_update().

hook_user() in Drupal 6 became (see User API page) hook_user_categories(), hook_user_insert(), hook_user_load(), hook_user_login(), hook_user_logout(), hook_user_presave(), hook_user_update(), and hook_user_view().

hook_block() in Drupal 6 became (see Block API page) hook_block_info(), hook_block_configure(), hook_block_save(), and hook_block_view().

The "form" and "register" operations have been removed. Use hook_form_alter instead.

Here are some examples - Drupal 6.x:

/**
* Implements hook_nodeapi().
*/
function book_nodeapi(&$node, $op, $teaser, $page) {
switch ($op) {
case 'load':
// Load a book.
}
}
/**
* Implements hook_node_type().
*/
function mymodule_node_type($op, $info) {
switch ($op){
case 'delete':
// Delete, insert or update according to $op.
}
}
/**
* Implements hook_user().
*/
function block_user($type, $edit, &$account, $category = NULL) {
switch ($type) {
case 'form':
// Construct the user form.
}
}
/**
* Implements hook_block().
*/
function system_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
// List blocks.
}
}
?>

Drupal 7.x:
/**
* Implements hook_node_load().
*/
function book_node_load($nodes, $types) {
// Load a book.
}
/**
* Implements hook_user_form().
*/
function block_user_form(&$edit, &$account, $category = NULL) {
// Construct the user form.
}

/**
* Implements hook_block_info().
*/

function system_block_info() {
// List blocks.
}

/**
* Implements hook_node_type_delete().
*/

function mymodule_node_type_delete($info) {
variable_del('comment_' . $info->type);
}

/**
* 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();
}
?>

2. hook_perm() renamed to hook_permission()

3.hook_footer() was removed, $closure became $page_bottom, $page_top added

4.hook_filter() and hook_filter_tips() replaced by hook_filter_info()
hook_filter() has been removed and replaced with hook_filter_info(), to allow modules to declare the input filters they provide using an associative array (hook_menu-alike registry structure), consistently with others info hooks in core.hook_filter_tips() is not required any more, since a 'tips callback' is provided in the hook_filter_info declaration, and used to generate filter tips.

Changes for Drupal 7 Module developers

1.Permissions have titles (required) and descriptions (optional)

2.Permissions are no longer sorted alphabetically, but are displayed in the order defined in your hook_permission().

3._comment_load() is now comment_load()

4.Module .info files must now specify all loadable code files explicitly

5.The {permission} table is gone, instead we have a {role_permission} which stores (role ID, permission string) pairs. Thus, each permission granted for a given role ID is a separate row in the table.

6.The new default type for items in forms or other structured array data (e.g. node content) passed to drupal_render() is '#type' => 'markup'. In Drupal 6 and earlier, the HTML content was added to the array using the #value attribute. In Drupal 7, this needs to be changed to #markup.

7.Use defined constant REQUEST_TIME instead of time()

8.referer_uri() has been removed and replaced with the PHP-provided global variable $_SERVER['HTTP_REFERER'].

9.Use absolute path (constructed from DRUPAL_ROOT) when including a file
Drupal 6.x:
// Allow specifying special cache handlers in settings.php, like
// using memcached or files for storing cache information.
require_once variable_get('cache_inc', './includes/cache.inc');
?>

Drupal 7.x:
// Allow specifying special cache handlers in settings.php, like
// using memcached or files for storing cache information.
require_once DRUPAL_ROOT . '/' . variable_get('cache_inc', 'includes/cache.inc');
?>

10.drupal_uninstall_module() is now drupal_uninstall_modules()

11.drupal_set_title() uses check_plain() by default

12.New user_cancel API
Users with the "administer users" permission are able to override the default method, f.e. to completely delete a user including all of the related content.

13.When using variable_get to retrieve variables, the $default parameter now defaults to NULL, so if you're getting a variable where you don't care about what the default is, then you don't have to pass "NULL" as the second parameter.

14.Changed parameters for drupal_add_js() and drupal_add_css()
The drupal_add_js() and drupal_add_css() functions now take either a string defining the type of script that's being added to the page, or an array defining more about the data being added.

Drupal 6.x:
drupal_add_js('misc/collapse.js', 'module');
drupal_add_js('misc/collapse.js', 'module', 'footer');
drupal_add_js('misc/collapse.js', 'module', 'header', FALSE, TRUE, FALSE);
drupal_add_css('/modules/devel/devel.css', 'module');
drupal_add_css('/modules/devel/devel.css', 'module', 'screen');
drupal_add_css('/modules/devel/devel.css', 'module', 'all', FALSE);
?>

Drupal 7.x:
drupal_add_js('misc/collapse.js'); // 'module' must be removed or else css will not be added!
drupal_add_js('misc/collapse.js', array('type' => 'module', 'scope' => 'footer'));
drupal_add_js('misc/collapse.js', array('preprocess' => FALSE));
drupal_add_css('modules/devel/devel.css');
drupal_add_css('modules/devel/devel.css', array('media' => 'screen'));
drupal_add_css('modules/devel/devel.css', array('preprocess' => FALSE));
?>

15.Changed Drupal.behaviors to objects having the methods 'attach' and 'detach'
Drupal 6.x:
Drupal.behaviors.tableSelect = function(context) {
$('form table:has(th.select-all):not(.tableSelect-processed)', context).each(Drupal.tableSelect);
};

Drupal 7.x:
Drupal.behaviors.tableSelect = {
attach: function(context) {
$('form table:has(th.select-all):not(.tableSelect-processed)', context).each(Drupal.tableSelect);
}
};

16.Schema descriptions are no longer translated

17.Replace 'core', 'module' and 'theme' with 'file' in drupal_add_js()

Drupal 6.x:
drupal_add_js($jquery_plugin, 'core');
drupal_add_js($module_javascript, 'module');
drupal_add_js($theme_javascript, 'theme');
drupal_add_js($other_javascript, 'module');
drupal_add_js($file);
?>

Drupal 7.x:
drupal_add_js($jquery_plugin, array('weight' => JS_LIBRARY));
drupal_add_js($module_javascript, array('type' => 'file', 'weight' => JS_DEFAULT));
drupal_add_js($theme_javascript, array('weight' => JS_THEME));
drupal_add_js($other_javascript, 'file');
drupal_add_js($file);
?>

18.New hook_js_alter to alter JavaScript

Drupal 6.x:
function jquery_update_preprocess_page(&$variables) {
// Modify the scripts variable.
if (!empty($variables['scripts'])) {
?>

Drupal 7.x:
function jquery_update_js_alter(&$javascript) {
// Modify the JavaScript being presented on the page.
?>

19.The datetime field type has been removed in favour of database engine specific types

Drupal 6:
$schema['mymodule_table'] = array(
'description' => 'My table',
'fields' => array(
'id' => array(
'description' => 'The id',
'type' => 'serial'
),
'calendar_dt' => array(
'description' => 'Date field',
'type' => 'datetime',
'not null' => FALSE,
),
),
);
?>

Drupal 7:
$schema['mymodule_table'] = array(
'description' => 'My table',
'fields' => array(
'id' => array(
'description' => 'The id',
'type' => 'serial'
),
'calendar_dt' => array(
'description' => 'Date field',
'mysql_type' => 'DATETIME',
'pgsql_type' => 'timestamp without time zone',
'not null' => FALSE,
),
),
);
?>

20.theme_pager() no longer takes limit parameter
Drupal 6:
theme('pager', $tags, $limit, $element, $parameters, $quantity);
?>

Drupal 7:
theme('pager', array('tags' => $tags, 'element' => $element, 'parameters' => $parameters, 'quantity' => $quantity));
?>

21.Custom menu API
In Drupal 6 in order to create a custom menu (i.e. a menu you would create via admin/build/menu/add) you had to query the {menu_custom} table yourself.
In D7 several API functions to create, update and delete custom menus and related hooks were added.

function foo() {
$menu = array(
'title' => 'My menu',
'menu_name' => 'my_menu',
'description' => 'My custom menu',
);
// Add a new custom menu.
menu_save($menu);
// Delete the custom menu.
// Although only the 'menu_name' key is required, we pass the full
// $menu, so other modules may act on it.
menu_delete($menu);
}

function foo_menu_delete($menu) {
if ($menu['menu_name'] == 'my_menu') {
drupal_set_mesasge(t('You have deleted the foo custom menu.'));
}
}
?>

22.drupal_eval() renamed to php_eval

23.Changes to HTTP header functions
drupal_set_header() now takes the header name and header value as two separate arguments rather than as one complete header line, and has been renamed to drupal_add_http_header. The function now also supports appending to and removing existing headers.

24.Changes to HTTP header functions
drupal_set_header('Content-Type: text/plain');
?>

Drupal 7.x:
drupal_add_http_header('Content-Type', 'text/plain');
?>

Check this link for more information http://drupal.org/update/modules/6/7

Sunday, January 2, 2011

Difference of Database API between drupal 6 & drupal 7

Normal Select queries:
----------------------
// Drupal 6
$result = db_query("SELECT nid, title FROM {node} WHERE uid = %d AND type = '%s'", 5, 'page');

// Drupal 7
$result = db_query("SELECT nid, title FROM {node} WHERE uid = :uid AND type = :type", array(
':uid' => 5,
':type' => 'page',
));
?>

Iterating a result set from db_query()
-------------------------------------
// Drupal 6
while ($record = db_fetch_object($result)) {
// Do stuff with $record, which is an object
}

// Drupal 7
foreach ($result as $record) {

// Do stuff with $record, which is an object
}
?>

Insert statements
-----------------
// Drupal 6
db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id();

// Drupal 7
$id = db_insert('mytable')
->fields(array(
'intvar' => 5,
'stringvar' => 'hello world',
'floatvar' => 3.14,
))
->execute();
?>

Update statements
-----------------
// Drupal 6
db_query("UPDATE {node} SET title='%s', status=%d WHERE uid=%d", 'hello world', 1, 5);

// Drupal 7
db_update('node')
->fields(array('title' => 'hello world', 'status' => 1))
->condition('uid', 5)
->execute();
?>

Delete statement
----------------
// Drupal 6
db_query("DELETE FROM {node} WHERE uid=%d AND created < %d", 5, REQUEST_TIME - 3600);

// Drupal 7
db_delete('node')
->condition('uid', 5)
->condition('created', REQUEST_TIME - 3600, '<')
->execute();
?>

CSS Hacks for Different Browsers

***** Selector Hacks ******/

/* IE6 and below */
* html #uno { color: red }

/* IE7 */
*:first-child+html #dos { color: red }

/* IE7, FF, Saf, Opera */
html>body #tres { color: red }

/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }

/* Opera 9.27 and below, safari 2 */
html:first-child #cinco { color: red }

/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho { color: red }

/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
#diez { color: red }
}

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
#veintiseis { color: red }
}


/* Safari 2 - 3.1 */
html[xmlns*=""]:root #trece { color: red }

/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: red }

/* Everything but IE6-8 */
:root *> #quince { color: red }

/* IE7 */
*+html #dieciocho { color: red }

/* Firefox only. 1+ */
#veinticuatro, x:-moz-any-link { color: red }

/* Firefox 3.0+ */
#veinticinco, x:-moz-any-link, x:default { color: red }



/***** Attribute Hacks ******/

/* IE6 */
#once { _color: blue }

/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#diecisiete { color/**/: blue }

/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */


Above are fast solution only but not the best solution

for ie best solution is create separate file for ie "ie.css" (for ie only):