Posts Tagged Drupal

How know Base Path of Drupal in JavaScript

Sometimes you want to know about the Base Path of your Drupal installation in JavaScript. You may want to know about this path for sending the AJAX request at correct URL relatively, load the image or some other type of file on client side through JavaScript etc.

Drupal provide a variable called Drupal.settings.basePath for this purpose in JavaScript. But this variable is only available if you include any custom JavaScript file or JavaScript block in your module. By default Drupal doesn’t include the ‘jquery.js‘ and ‘drupal.js‘ file in generated output. It only add these files if you add your custom JavaScript file or JavaScript block. We can include our custom JavaScript file in Drupal like this:-

drupal_add_js(drupal_get_path('module','my_module'). '/my_module.js');

The my_module.js file should reside in same directory where my_module module exist. This will force Drupal to add jquery.js and drupal.js files in output.

These two files initialize the Base Path variable. In drupal.js file, on top you can see the initialization of setting object in Drupal object. Like this:-

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };

Drupal generate some JavaScript code in Script block inside head tag of each page for extending the settings object with the help of jQuery. Like this:-

jQuery.extend(Drupal.settings, { "basePath": "/" });

You can test the Base Path by adding following code in my_module.js file.

$(document).ready(function() {
	alert(Drupal.settings.basePath);
});

This will alert the Base Path for Drupal installation after loading of the page.

, ,

No Comments


Create Drupal form using theme_table() like module list form (Part II)

This post is the second part of Create Drupal form using theme_table() like module list form post. In first part I have showed how we can create Drupal form like we have in Module list pages. In this post, I am showing how we disable some of the checkboxes so user can’t select them like we have for core modules in module list page. We can’t enable/disable core modules in module list.

Drupal Form using theme_table() function (Part II)

Drupal Form using theme_table() function (Part II)

Here I am just showing the changes which we require in code of Part I post.

 $form['featured'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    '#default_value' => $status,
);
 
// Change this to 
 
$form['featured'] = array(
    '#type' => 'checkboxes',
    '#options' => $options,
    '#default_value' => $status,
    '#process' => array(
        'expand_checkboxes',
        'featured_disable',
        ),
    '#disabled_products' => $disabled,
);

In above code “$disabled” is an array containing the productid’s of all the products which we want to show as checked and in disable state. The structure of “$disabled” array is similar to “$status” array. We stored this array in “#disabled_products”. We also added “#process” in above code.

“expand_checkboxes” and “featured_disable” are function names which Drupal call when create and render these checkboxes. “expand_checkboxes()” is defined in Drupal core files and we don’t need to define it again.

function featured_disable($form, $edit) {
  	foreach ($form['#disabled_products'] as $key) {
  		$form[$key]['#attributes']['disabled'] = 'disabled';
  	}
 
  	return $form;
}

“featured_disable()” function is very important here. Drupal call this function when renders these checkboxes. Here we assigned “disabled” attribute to each checkbox which we want as disable.

, ,

4 Comments


How use AJAX in DRUPAL

How use AJAX in DRUPAL

How use AJAX in DRUPAL


We can easily use AJAX in DRUPAL framework. Drupal provide the jQuery javascript library so we can use jQuery for our AJAX implementation. First we write a module in which we are going to implement the server side logic. Suppose our module name is product and we will check the given product name is exist or not in our product table.

<?php
/*product.module*/
 
function product_menu() {
  	$items = array();
 
	$items['product'] = array(
		'page callback' => 'drupal_get_form',
		'page arguments' => array('product'),
    		'access arguments' => TRUE,
    		'type' => MENU_CALLBACK,
  	);
 
  	$items['product/check_name'] = array(
    		'page callback' => 'check_name',
    		'access arguments' => TRUE,
    		'type' => MENU_CALLBACK,
  	);
 
  	return $items;
}
 
function product() {
	$path = drupal_get_path('module', 'product');
	drupal_add_js($path . '/product.js', 'module');
 
	$form['product_name'] = array(
		'#title' => t('Product Name'),
		'#type' => 'textfield',
		'#required' => TRUE,
		'#size' => 30,
		'#description' => t('Please enter product name.'),
	);
 
	$form['check_name'] = array(
		'#type' => 'markup',
		'#value' => "<a href='#' id='check_name'>" . t('Check Product Name') . "</a><br/>",
	); 
 
	$form['status'] = array(
		'#type' => 'markup',
		'#value' => "<span id='status'></span><br/>",
	); 
 
	$form['submit'] = array(
		'#type' => 'submit',
		'#value' => t('Submit'),
	);
 
	$form['cancel'] = array(
		'#type' => 'markup',
		'#value' => l(t('Cancel'), 'product_mgmt'),
	); 
	return $form;
}
 
function check_name() {
	$name = strtolower($_GET['name']);
 
	$query = "SELECT COUNT(*) AS total FROM {product} WHERE LOWER(product_name) LIKE ('%s')";
	$rs = db_query($query, $name);
 
	$info = db_fetch_object($rs);
	$total = $info->total;
 
	if ($total) {
		echo "$('#status').html('This product is available.');";
	}
	else {
		echo "$('#status').html('This product is not available.');";
	}
}
?>

Don’t return anything in “check_name()” function otherwise it will return the whole page when we access “product/check_name” path through AJAX.

/*product.js*/
 
// JavaScript Document
$(document).ready(function() {
	$('#check_name').attr('href', 'javascript:void(0);');
 
	$('#edit-product-name').keydown(function(event){
		$('#status').html('');
	});
 
    $('#check_name').click(function() {
		var name = $.trim($('#edit-product-name').val());
 
		if (name == '') {
			$('#status').html('Please enter product name.'); return;
		}
 
		$.ajax({
   			type: "GET",
			url: "/product/check_name",
   			data: "name=" + encodeURI(name),
   			success: function(msg){
				eval(msg);
   			}
 		});
	});
});

, ,

12 Comments


Hide a Menu from Admin in Drupal

Suppose you want to create a Menu and don’t want to show it to Admin. Admin or Administrator is the first user of your Drupal website and it has all the access. Normally the user id (uid) of admin is 1. So, you can hide a menu from admin using the “access callback” in “menu_hook“. Lets say our module name is “test”.

<?php
/*** 
Implementation of hook_menu().  
*/ 
function test_menu() {   	
	$items = array();    
 
	$items['earnings'] = array(     		
		'title' => t('Earnings'),     		
		'page callback' => 'earnings',     		
		'access callback' => 'check_user',   	
	);      	
	return $items; 
}  
 
function check_user() { 	
	global $user; 	 	
 
	if ($user->uid == 1) { 		
		return FALSE; 	
	} 	 	
 
	return TRUE; 
} 
?>

Here we have used an “access callback” function “check_user()” for menu “earnings”. In “check_user()” function we have checked the uid of currently logged in user. If the currently logged in user is admin (uid = 1) then we return FALSE otherwise we returned TRUE.

No Comments


Create a sortable table using “theme_table()” function in Drupal

Sortable table using theme_table() function

Sortable table using theme_table() function


We can create a sortable header using “theme_table()” function. In sortable header user can sort a column in ascending or descending order. I am using a table called “package_coupon“. This table have seven fields (coupon, operator, operand, created, expire, used and user_by). We are providing the sorting facility on four fields only (coupon, created, expire and used). Initially, the coupon field is sorted by ascending order.

Here “tablesort_sql()” function is important. This function produces the ORDER BY clause to insert in your SQL queries, assuring that the returned database table rows match the sort order chosen by the user.

Code:-

function package_coupon_list() {
	$head = array(
		array('data' => t('Coupon'), 'field' => 'coupon', 'sort' => 'asc'),
		array('data' => t('Type of Discount')),
		array('data' => t('Created'), 'field' => 'created'),
		array('data' => t('Expire'), 'field' => 'expire'),
		array('data' => t('Status'), 'field' => 'used'),
		array('data' => t('Used by')),
	);
 
  	$sql = "SELECT * FROM package_coupon" . tablesort_sql($head);
 
   	$result = db_query($sql);
 
  	while ($coupon = db_fetch_object($result)) {
		$rows[] = array(
			array('data' => _coupon_format($coupon->coupon)),
			array('data' => ($coupon->operator == '%' ? "{$coupon->operand}% discount" : "\${$coupon->operator}{$coupon->operand} discount")),
			array('data' => format_date($coupon->created, 'small')),
			array('data' => format_date($coupon->expire, 'small')),
			array('data' => $coupon->used . ' left'),
			array('data' => ($coupon->user_by == '') ? 'None' : $coupon->user_by),
		);
  	}
 
	return theme_table($head, $rows);
}

6 Comments