Saturday, 30 May 2015

How to check whether a region contains block for current page?

At some cases, we might need to add some div structures to a group of regions, at that case, we need to check whether region has any block or not to place the div structure.
Code in page.tpl.php
<?php if(region_empty($testRegion1)) { 
<div id="testId">
print $testRegion1;
 print $testRegion2;
 print $testRegion3; 
 print $testRegion4;
The function region_empty() would return 1 if it has a block to show.
function region_empty($test_region) {
  $test_empty = 1;
  $result = db_query_range('SELECT n.pages, n.visibility FROM {blocks} n WHERE n.region="%s" AND n.theme="%s"', $test_region, $GLOBALS['theme'], 0, 10);
  if (count($result) > 0) {
    while ($node = db_fetch_object($result))
      if ($node->visibility < 2) {
        $path = drupal_get_path_alias($_GET['q']);
        // Compare with the internal and path alias (if any).
        $page_match = drupal_match_path($path, $node->pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $node->pages);
        $page_match = !($node->visibility xor $page_match);
      } else {
        $page_match = drupal_eval($block->pages);
      if ($page_match)
        $test_empty = 0;
  return $test_empty;

How to add custom styles to form elements in template.php file?

/*To add styles to form elements in template.php file*/
function theme_form_element($element, $value) {
// This is also used in the installer, pre-database setup.
$t = get_t();
$output = '<div class="form-item"';
if (!empty($element['#id'])) {
$output .= ' id="'. $element['#id'] .'-wrapper"';
$output .= ">\n";
$required = !empty($element['#required']) ? '<span class="form-required" title="'. $t('This field is required.') .'">* </span>' : '';
if (!empty($element['#title'])) {
$title = $element['#title'];
if (!empty($element['#id'])) {
$output .= ' <label for="'. $element['#id'] .'">'. $t('!title !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
else {
$output .= ' <label>'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
$output .= " $value\n";
if (!empty($element['#description'])) {
$output .= ' <div class="description">'. $element['#description'] ."</div>\n";
$output .= "</div>\n";
return $output;
/* It would be possible to add styles to individual elements*/
function theme_button($element) {
   if (isset($element['#attributes']['class'])) {
    $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
  else {
    $element['#attributes']['class'] = 'form-'. $element['#button_type'];
  return '<input type="'.(isset($element['#button_type']) ? $element['#button_type'] : "submit").'" '. (empty($element['#name']) ? '' : 'name="'. $element['#name'] .'" ') .'id="'. $element['#id'] .'" value="'. check_plain($element['#value']) .'" '. drupal_attributes($element['#attributes']) ." />\n";
/* For Fieldset */
function phptemplate_fieldset($element) {
  if ($element['#collapsible']) {
    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = '';
    $element['#attributes']['class'] .= ' collapsible';
    if ($element['#collapsed']) {
     $element['#attributes']['class'] .= ' collapsed';
  return '<fieldset'. drupal_attributes($element['#attributes']) .'>'. ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') .'<div class="top"><div class="bottom"><div class="bottom-ornament">'. (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . (!empty($element['#children']) ? $element['#children'] : '') . $element['#value'] ."</div></div></div></fieldset>\n";

Added fields to content type, selected input type to allow PHP, however, while printing it, the PHP things are not getting rendered, any solution?

We have to use drupal_eval() in that case.
This function will render the PHP data.

When moved contents from one site to another, some contents were not came in the list, what would be the reason?

DRUPAL would check the authorization while retreving the content.
Hence, if the author is not available in the site, it wouldn't show the associated content.
Dev environment logins wont be available in QA environment.  Hence, it would be good to change the author name to admin or make it blank  while creating contents if planned to move the content.

How to include css and js files in theme info file?

It could be possible to include js and css files in theme info file itself, eventhough, those are not in themes folder.
One more thing, if we include these files through link / script tags, while doing aggregation (cache), DRUPAL wont cache those files.
stylesheets[all][] = ../../../default/files/styles/style.css
stylesheets[all][] = style1.css
conditional-stylesheets[if IE 7][all][] = ../../../default/files/styles/style_ie7.css
conditional-stylesheets[if IE 8][all][] = ../../../default/files/styles/style_ie8.css

scripts[]= ../../../default/files/javascript/AC_RunActiveContent.js
scripts[]= ../../../default/files/javascript/swfobject.js
In the above ex, style.css file is in a folder which is in sites/default/files ... path. 
It is similar in case of scripts too.
And we can see the way to include conditional style sheets for IE browser.  This could be possible with Conditional Styles module.  For more info,

How to remove auto completion for text fields in DRUPAL?

Add the following attribute to form variable, autocomplete="off"
$form['firstname'] = array(
            '#type' => 'textfield',
            '#weight' => 0,
            '#attributes' => array(

Usage of system_settings_form() function

We can store the entered field values by default, if we use the form variables as variable names,
function custom_settings() {
$form['disclaimer_content'] = array(
           '#type' => 'textarea',
           '#required' => True,
           '#title' => t('Disclaimer Content'),
           '#default_value' => variable_get('disclaimer_content',''),
           '#description' =>  t('Enter Disclaimer content.'),
return system_settings_form($form);

Is there any naming conventions for the folders in files folder

DRUPAL would create folders ( JS and CSS ) inside the FILES folder whenever we cache js and css. 
Hence, eventhough we named custom folders as JS/CSS, DRUPAL would delete all the files in those folders while clearing the cache.
So, if we named our custom folders in FILES folder as JS / CSS.  Whenever, we cleared the cache, DRUPAL would delete the files in those folders.

How to retrieve all the items of a menu tree and display with customized UI in Drupal 6

We can use the menu funtion menu_tree_all_data(), which war available in file.  Need to pass the menu name with prefix of 'menu-' as a paramenter for this function.
Ex :
Let us create one menu with name as "test-menu".  And create few items in it, such as Menu1, Menu2, Menu3 as a sub link of Menu1 (Menu1--->Menu3). Now, whenever, we click on that menu under site building -> Menu section, the url would be with "menu-test-menu" as a last argument.  We need pass this one as a paramenter to the function menu_tree_all_data() as follows:
$menu_tree = menu_tree_all_data("menu-test-menu");
It would return an array which has  main menus (such as Menu1, Menu2 ) as keys, and values consists of array with two key-value pairs, keys are "link", "below". Here, the key "link" would associate with details of current menu which includes a key 'has_children', it would be '1' if the current menu has sub-links.  And the key "below" would associate with the sub-links details if any.
function get_sitemap() {

$menu_items = menu_tree_all_data('menu-test-menu');
foreach($menu_items as $key => $value) {
$output .= "<a href='".url($value['link']['link_path'])."' title='".$value['link']['link_title']."' >".$value['link']['link_title']."</a><br/>";
if($value['link']['has_children']) {
$output = add_child_menus($value['below'],$output);
return $output;
function add_child_menus($child_menus = array(),$output = null) {
foreach ($child_menus as $child_key => $child_value) {
$output .= "<a style='margin-left:".$child_value['link']['depth']."0px' href='".url($child_value['link']['link_path'])."' title='".$child_value['link']['link_title']."' >".$child_value['link']['link_title']."</a><br/>";
if($child_value['link']['has_children']) {
$output = add_child_menus($child_value['below'],$output);
return $output;
Here, in the get_sitemap() function, checking whether menu item has children or not, if TRUE, calling the recursive function add_child_menus() with the value associated with "below" key and current string.  Function add_child_menus() would recheck each and every sublink and associated links and returns the final output which has all menus with corresponding sublinks.  We can add classes in the anchor tags and place respective CSS.

What are the mandatory fields to write .info file for module in DRUPAL 6?

.info file should have the same name as .module file and it should be in the same folder in which the later one exists.
name, description and core are the mandatory fields for .info files in modules.

Format :
name : 
name = "Test module"   ---   This is Drupal Capitalization Standard to have a capital letter as the first letter of the first word.  This is used as a display name for this module to admin.

descpirtion :
description = "This is description for Test module."   ---   This is useful to explain the purpose of your module in brief.  It has a limitation to have 255 characters.

core :
core = 6.x   ---   This is DRUPAL version but not the specific version like 6.3

Hence, here is the entire contents of .info file which has only mandatory fields:
name = "Test module"
description = "This is description for Test module."
core = 6.x

The following are some of the optional fields for .info file of module :
dependencies[]   ---   It is an array which contains the modules which needs to be enabled for the current module functionality.
package   ---   Used to group modules which might have internal dependencies.
php   ---   Used to mention the required php version for this module to work in proper.

How to add meta keywords, description for menus created through modules dynamically?

We might face a requirement where we need to place the meta data for a page dynamically based on user activity. For eg., search pages.
We can use drupal_add_html_head to add meta data for a page.
    $pageKeywords = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'keywords',
            'content' => 'custom meta keywords',
    $pageDescription = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'description',
            'content' => 'custom meta description',
   $pageTitle = 'page title';
    drupal_add_html_head($pageKeywords, 'page_keywords');
    drupal_add_html_head($pageDescription, 'page_description');

How to add custom jQuery instead of default for end user theme in Drupal 7?

/* We can use hook_js_alter for altering the JS files in template.php so that the updated jQuery would be used for only the pages where this is loaded.*/
function THEME_NAME_js_alter(&$javascript) {
// Swap out jQuery to use an updated version of the library.
global $base_url;
$jQuery_version = '1.11.1';
$jQuery_local = $base_url.'/'.drupal_get_path('theme', 'THEME_NAME') . '/js/jquery-1.11.1.js';
$javascript['misc/jquery.js']['data'] = $jQuery_local;
$javascript['misc/jquery.js']['version'] = $jQuery_version;

How to add field collections to node through code in Drupal 7?

//Load the node details:
$nid = 10;
$node = node_load($nid);
$language = $node->language;
//Create Field Collection Item:
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_collection_1'));
        $field_collection_item->setHostEntity('node', $node);
        $field_collection_item->field_one[$language][0]['value'] = t('Value One');
        $field_collection_item->field_two[$language][0]['value'] = t('Value Two');

How to get week starting date of a date in PHP?

$W = date('W',strtotime(date('Y-m-d'))); // Get the week number
$sunday = date(datetime::ISO8601, strtotime(date('Y') . "W" . $W . "0")); // "0" means Sunday, "1" means Monday, ... , "7" means next Sunday
echo date('Y-m-d',strtotime($sunday));
$nextSunday = date(datetime::ISO8601, strtotime(date('Y') . "W" . $W . "7"));
echo date('Y-m-d',strtotime($nextSunday));

How to replace contents of fields in Drupal 7?

Prepare a menu item for selecting the field name, providing the search text & replace text.
 * Implements hook_menu().
 function custom_menu() {
    $items = array();
/* To replace content like URL's in body fields */
    $items['admin/config/development/replace-content'] = array(
        'title' => 'Replace Content',
        'description' => t("To replace contents like URL's in Body field when Database deployed from different environment"),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('replace_content'),
        'access arguments' => array('replace content'),
return $items;
 * Configuration form for Replacing Contents in the Database based on the selected fields
function replace_content($form, &$form_state){
  global $base_url;
    $fieldsList = field_info_field_map();
    $field_arr = array();
    if(is_array($fieldsList) && count($fieldsList)){
        foreach($fieldsList as $fieldName => $fieldDetails){
            $field_arr[$fieldName] = $fieldName;
    $form['search_parameter'] = array(
            '#type' => 'textfield',
            '#title' => t('Enter text to search in body field'),
            '#default_value' => '',
            '#required' => TRUE
    $form['replace_parameter'] = array(
            '#type' => 'textfield',
            '#title' => t('Enter text to replace in body field'),
            '#default_value' => $base_url,
            '#required' => TRUE
    $form['search_in_fields'] = array(
            '#type' => 'select',
            '#title' => 'Fields',
            '#options' => $field_arr,
            '#description' => t('Select the fields in which the content has to get replace'),
            '#multiple' => TRUE,
            '#required' => TRUE
    $form['submit'] = array( '#type' => 'submit', '#value' => t('Replace'));
    return $form;
/* Replace content submit function */
function replace_content_submit($form, &$form_state){
    $values = $form_state['values'];
    $search_parameter = $values['search_parameter'];
    $replace_parameter = $values['replace_parameter'];
    $search_in_fields = $values['search_in_fields'];
    $affected_rows_exists = FALSE;
    foreach($search_in_fields as $selected_field){
            $table_name = 'field_data_' . $selected_field;
            $revision_table_name = 'field_revision_' . $selected_field;
            $field_name = $selected_field . '_value';
                    $affected_rows = db_update($table_name)
  ->expression($field_name, "replace($field_name, :search, :replace)", array(':search' => $search_parameter, ':replace' => $replace_parameter))
                            $affected_rows_exists = TRUE;
                            $row_text = (count($affected_rows)>1) ? 'rows' : 'row';
                            drupal_set_message(t($affected_rows . ' ' . $row_text .  ' got affected in ' . $table_name . '.'));
                    $affected_revision_rows = db_update($revision_table_name)
  ->expression($field_name, "replace($field_name, :search, :replace)", array(':search' => $search_parameter, ':replace' => $replace_parameter))
                            $affected_rows_exists = TRUE;
                            $row_text = (count($affected_revision_rows)>1) ? 'rows' : 'row';
                            drupal_set_message(t($affected_revision_rows . ' ' . $row_text . ' got affected in ' . $revision_table_name . '.'));
            drupal_set_message(t('None of the rows got affected.'));