Archive for May, 2009

Theme Drupal Form

In this example, we are theming Drupal form different from its default layout. Suppose we have a search form with two fields search textbox and category selectbox. We are assuming that our module name is “search“.

Default Layout Search Form

Default Layout Search Form



Themed Layout Search Form

Themed Layout Search Form


Step 1. Create search form using Drupal Form API.

function search_form() {
	$form['str'] = array(
	'#type' => 'textfield',
	'#size' => '32',
	);
 
	$form['category'] = array(
	'#name' => t('category'),
	'#type' => 'select',
	'#options' => array('0' => t('All'), '1' => t('Bars'), '2' => t('Restaurants')),
	);
 
	$form['submit'] = array(
	'#type' => 'submit',
	'#value' => t('Search'),
	);
 
	return $form;
}

Step 2. Register our theme in Drupal theme registry using hook_theme().

function search_theme() {
  global $theme;
 
  return array(
    'search_form' => array(
      'arguments' => array('form' => NULL, 'theme' => $theme),
      'template' => 'search-form',
    ),
  );
}

Step 3. Create search-form.tpl.php file to theme this search form.

<table cellspacing="0">
	<tr>
    	<td class="container-inline"><strong><?php print t('Search');?></strong> <?php print drupal_render($form['str']); ?></td>
        <td class="container-inline"><strong><?php print t('Category');?></strong> <?php print drupal_render($form['category']); ?></td>
        <td><?php print drupal_render($form['submit']); ?></td>
    </tr>
</table>
<?php
print drupal_render($form);
?>

,

3 Comments


Hide Input Format Options from Drupal Node Create Form

Normally you don’t want to show “Input Format” options available in node create form to your website users. You can easily hide them using CSS. We are hiding these options only from normal users and not from admin user.

Input Format

Input Format



1. Create a hook_form_FormID_alter callback function to add the ID to DIV that containing the Input Format options. Suppose our module name is “story” and we want to hide Input Format options from “Create Story” form. So, our callback function name should be story_form_story_node_form_alter(). Where “story_node_form” is Form ID of create story form.

function story_form_story_node_form_alter(&$form, &$form_state) {
	global $user;
 
	if ($user->uid != 1) {
		$form['format']['#attributes'] = array('id' => 'fieldset-input-format');
	}
}

2. We added the ID “fieldset-input-format” to DIV containing Input Format options. Now, we need to hide it using CSS.

#fieldset-input-format {
	display:none;
}

,

3 Comments


Create or Move Google Map Marker Like twittervision.com

Move Google Map like twittervision.com

Move Google Map Marker like twittervision.com



Check out the demo here.

In this example I am showing how we can move marker on Google Map. This example is inspired by twittervision.com. Here we are changing information on Marker and moving it on Google Map using AJAX and JavaScript. We are refreshing the list of available updates from server in a fixed interval.

1. HTML File

<!--index.html-->
<html>
<head>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAMEzhSKcWoYFZdcgJ2yb9VhQfbBedyeTcqIokiCHhEBJKH_N_NRTEMzJanHbfvVY9Llw4oYuILWGf5Q" type="text/javascript"></script>
<script src="prototype.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
<style type="text/css">
.map {
	width: 800px;	height: 400px;	border:#666666 thin dashed;
	padding: 0;	background: #FFFFFF;	margin-right: auto;	margin-bottom: 10px;
	margin-left: auto;
}
#lastStatus {
	font-size:12px;	font-family: verdana, arial, helvetica, sans-serif;
	color:#333;	padding:5px;
}
#infoWindow {
	width:350px; text-align: left;
}
#infoWindow tip {
	float: right;
}
</style>
</head>
<body>
  <div id="map" class="map"></div>
</body>
</html>

2. JavaScript File

//script.js
 
var infos = [];
var loading = false;
var displayCount = 0;
 
function Info (infoArray) {
	var infoVars = [ 'latitude', 'longitude', 'location_name', 'text'];
 
	for (var i = 0; i < infoVars.length; i++) {
		this[infoVars[i]] = infoArray[i];
	}
}
 
 
Info.prototype.lastStatus = function () {
	var myDiv = document.createElement('div');
	myDiv.innerHTML = this.text;
	myDiv.id = "lastStatus";
 
	return myDiv;	
}
 
Info.prototype.infoWindow = function() {
	var myInfoWindow = document.createElement('div');
	myInfoWindow.id = "infoWindow";
	myInfoWindow.appendChild(this.lastStatus());
 
	return myInfoWindow;
}
 
function loadData() {
	if (!loading) {
		new Ajax.Request('updates.php', { 
			method : 'post',
			onCreate : function () { loading = true; },
			onSuccess : function(transport) {addInfos(transport.responseText);},
			onComplete : function () { loading = false; } 
		});
	}
}
 
function showInfos() {
	var currentInfo = infos.pop();
	if ( currentInfo && currentInfo.show ) {
		currentInfo.show();
		displayCount++;
	}
	if (infos.length == 0)
		loadData();
 
	setTimeout("showInfos();", 5000);
}
 
function addInfos(responseText) {
	var newInfos = eval(responseText);
	if (newInfos.length == 0)
		alert("No Infos Available!");
	else {	
		for (i=0; i<newInfos.length; i++) {
			infos.push(new Info(newInfos[i]));
		}
	}
	if (displayCount == 0)
		showInfos();
}
 
var map;
var userMarker;
var marker;
 
var map_icon = addOptionsToIcon(new GIcon(),{iconSize : new GSize(48,48), iconAnchor : new GPoint(18,43), infoWindowAnchor : new GPoint(45,20), image : '/images/icon.png', shadow : '/images/birdshadow.png'});
 
// add options to a GMaps icon
function addOptionsToIcon(icon, options) {
	for(var k in options)	{
		icon[k] = options[k];
	}
	return icon;
}
 
function loadMap () {
	var w = 800; // Width of map container
	map = new GMap2(document.getElementById("map"), {mapTypes: [G_PHYSICAL_MAP] });
	map.setCenter(new GLatLng(39,76), w>700 ? 3 : 2);
	map.addControl(new GSmallMapControl());	
}
 
Info.prototype.show = function () {
	// clear marker
	map.closeInfoWindow();
	if (marker)
		map.removeOverlay(marker);
 
	// show marker with infoWindow
	marker = new GMarker(new GLatLng(this.latitude,this.longitude), { icon : map_icon });
	map.addOverlay(marker);
	map.openInfoWindow(marker.getLatLng(), this.infoWindow(), {noCloseOnClick : true, pixelOffset : new GSize(25,-22) } );
}
 
addEvent(window, 'load', init);
 
function init() {
	if (GBrowserIsCompatible()) {    
		loadMap();
		loadData();
	} else {
		alert("Sorry, your browser isn't compatible with Google Maps!")
	}
}
 
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}

3. PHP File

<?php
//updates.php
 
header('Content-Type: text/javascript; charset=utf-8');
$info[] = array(34.1372273,-117.7023255,"Los Angeles, New Orleans", "Manny Pacquaio's two-round demolition of Ricky Hatton has set up the prospect of the biggest money-spinning fight in the history of boxing.");
$info[] = array(52.6449251,-0.6424268,"England near Rutland Water", "Liverpool, with returning captain Steven Gerrard back in the side, were always in control against a disappointing Newcastle -- who have still to collect their first victory under temporary manager Alan Shearer.");
$info[] = array(37.775,-122.418333,"San Francisco", "Dirk Kuyt squared a dangerous ball into the six-yard box and Israeli Benayoun slid home his fourth goal from seven games, as three defenders stood and watched.");
$info[] = array(40.757929,-73.985506,"New York, NY", "That lead was doubled just six minutes later when Gerrard's corner was met with a superb diving header from Dutchman Kuyt, giving Steve Harper no chance in the Newcastle goal.");
$info[] = array(48.751448,-122.472574,"bellingham, wa", "Xabi Alonso hit the crossbar for Liverpool with a curling 30-yarder as Newcastle struggled to get a foot-hold on the game.");
$info[] = array(45.823041,6.197545,"Here.", "Alonso was stretchered off following that tackle and his replacement Lucas Leiva added a third goal in the 88th-minute when heading home Fabio Aurelio's free-kick.");
$info[] = array(39.755092,-104.988123,"Los Angeles", "The result leaves Liverpool three points behind leaders Manchester United, although Alex Ferguson's side have a game in hand.");
$info[] = array(27.800278,-97.396111,"corpus christi", "Meanwhile, Newcastle remain second bottom on 31 points, level with north-east rivals Middlesbrough who they face next weekend in a crucial showdown, with just three matches remaining.");
 
echo json_encode($info);
?>

, ,

5 Comments


Simple Implementation of Javascript Check and Uncheck All Checkboxes

Javascript Check and Uncheck All Checkboxes

Javascript Check and Uncheck All Checkboxes



A simple example of check and uncheck all checkboxes implementation using javascript. We have created a set of checkboxes under a DIV called container. There is a checkbox at the top for check or uncheck all the checkboxes. We have added a function on the click event of top checkbox and when user click it we check its state as checked or unchecked and assign that state to all the other checkboxes.

Check out the demo here.


JavaScript Code:

<script language="javascript" type="text/javascript">
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}
 
addEvent(window, 'load', initCheckboxes);
 
function initCheckboxes() {
	addEvent(document.getElementById('all'), 'click', setCheckboxes);
}
 
function setCheckboxes() {
	var cb = document.getElementById('container').getElementsByTagName('input');
 
	for (var i = 0; i < cb.length; i++) {
		cb[i].checked = document.getElementById('all').checked;
	}
}
</script>

HTML Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check/Uncheck ALL Checkboxes</title>
<style type="text/css">
.container { width:300px}
.odd { background-color: #edf5fa;}
.even { background-color: #fff;}
.all { border-bottom:#666666 thin dashed; margin-bottom:4px;}
</style>
</head>
<body>
    <div class="container">
    	<div class="all"><label><input type="checkbox" name="cb" value="1" id="all" />Check All</label> </div>
    </div>
    <div class="container" id="container">
    	<div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Elephant</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Lion</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Tiger</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Horse</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Anaconda</label> </div>
        <div class="even"><label><input type="checkbox" name="cb[]" value="1" />Bear</label> </div>
        <div class="odd"><label><input type="checkbox" name="cb[]" value="1" />Leopard</label> </div>
    </div>
</body>
</html>

,

1 Comment


Upload image using hidden iFrame (Simple Photo Manager)

Image Upload Using iFrame

Image Upload Using iFrame

You can view the working demo here.

You can download the source code here.

In this example we are using a hidden IFrame for uploading file without refreshing page.

Include IFRAME in your page.

<div id="iframe_container">
        <iframe src="pm-upload.php" frameborder="0" style="height:75px;"></iframe>
</div>

The pm-upload.php has a FROM with file input field. When user select a file for upload we have called a upload() function on onChange event of file element.

<form name="iform" action="" method="post" enctype="multipart/form-data">
    <input id="file" type="file" name="image" onChange="window.parent.upload(this);" /><br>
    <span style="font-size:11px; color:#666666;">only gif, png, jpg files.</span>
    <input type="hidden" value="" name="div_id" />
</form>

If file successfully upload and satisfy all validation conditions then we call setUploadedImage() function to setup the information of recently uploaded file on parent window. we can access the parent window javascript functions like this:

window.parent.setUploadedImage();

If there is some validation error then we call uploadError() function of parent window.

Here is complete javascript code for this tutorial:

//Call at the time of upload
function upload(fileObj){
	var par = window.document;
	var frm = fileObj.form;
	var div_id = parseInt(Math.random() * 100000);
 
	// hide old iframe
	var iframes = par.getElementsByTagName('iframe');
	var iframe = iframes[iframes.length - 1];
	iframe.className = 'hidden';
 
	// create new iframe
	var new_iframe = par.createElement('iframe');
	new_iframe.src = 'pm-upload.php';
	new_iframe.frameBorder = '0';
	new_iframe.style.height = '75px';
	par.getElementById('iframe_container').appendChild(new_iframe);
 
	// add image progress
	var images = par.getElementById('images_container');
	var new_div = par.createElement('div');
	new_div.id = div_id;
 
	var new_img = par.createElement('img');
	new_img.src = 'images/indicator2.gif';
	new_img.style.marginLeft = '33px';
	new_img.style.marginTop = '50px';
	new_div.appendChild(new_img);
	images.appendChild(new_div);
 
	var errorDiv = par.getElementById('error');
	errorDiv.innerHTML = "";
	errorDiv.style.display = 'none';
 
	// send
	frm.div_id.value = div_id;
	setTimeout(frm.submit(),5000);
}
 
//Call when upload completed
function setUploadedImage(imgSrc, fileTempName, divId) {
	var par = window.document;
 
	var images = par.getElementById('images_container');
 
	var imgdiv = par.getElementById(divId);
	var image = imgdiv.getElementsByTagName('img')[0];
	imgdiv.removeChild(image);
 
	var image_new = par.createElement('img');
	image_new.src = imgSrc;
	image_new.className = 'pic';
 
	var image_label = par.createElement('input');
	image_label.type = "text";
	image_label.maxLength = "40";
	image_label.size = "12";
	image_label.value = "Label";
	image_label.name = "title[]";
 
	var image_hidden = par.createElement('input');
	image_hidden.type = "hidden";
	image_hidden.value = "1";
	image_hidden.name = "delFlag[]";
 
	var image_name = par.createElement('input');
	image_name.type = "hidden";
	image_name.value = fileTempName + ",new";
	image_name.name = "imageName[]";
 
	var image_del_link = par.createElement('a');
	image_del_link.href = "javascript:void(0)";
	image_del_link.appendChild(par.createTextNode("Delete"));
 
	var br = par.createElement('br');
 
	imgdiv.appendChild(image_new);
	imgdiv.appendChild(image_label);
	imgdiv.appendChild(image_hidden);
	imgdiv.appendChild(image_name);
	imgdiv.appendChild(br);
	imgdiv.appendChild(image_del_link);
 
	image_label.onfocus = function() {
		eval(labelOnFocus(image_label));
	}
 
	image_label.onblur = function() {
		eval(labelOnBlur(image_label));
	}
 
	image_del_link.onclick = function() {
		eval(deleteLinkOnClick(image_del_link, ''));
	}
}
 
// call when error occurred at the time of upload
function uploadError(divId, oName) {
	var par = window.document;
	var images = par.getElementById('images_container');
	var imgdiv = par.getElementById(divId);
	images.removeChild(imgdiv);
	var errorDiv = par.getElementById('error');
	errorDiv.innerHTML = oName + " has invalid file type.";
	errorDiv.style.display = '';
}
 
function labelOnFocus(image_label) {
	if (image_label.value == "Label") {
		image_label.value = "";
	}
}
 
function labelOnBlur(image_label) {
	if (image_label.value == "") {
		image_label.value = "Label";
	}
}
 
function deleteLinkOnClick(delLink, delFlag) {
	var par = window.document;
	var imgDiv = delLink.parentNode;
	var image_hidden = delFlag == '' ? imgDiv.childNodes[2] : par.getElementById(delFlag);
 
	if (image_hidden.value == '1') {
		image_hidden.value = '0';
		delLink.removeChild(delLink.childNodes[0]);
		delLink.appendChild(par.createTextNode("Restore"));
		delLink.style.color = '#FF0000';
	}
	else {
		image_hidden.value = '1';
		delLink.removeChild(delLink.childNodes[0]);
		delLink.appendChild(par.createTextNode("Delete"));
		delLink.style.color = '#64B004';
	}
}

You can check the live demo of this tutorial and you can also download the source code of the sample demo. The demo example is very simple and only for learning purpose. You can easily extent the sample code as per your requirement.

, , ,

16 Comments