Archive for May, 2009

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);
}

5 Comments


A Simple Modal Window Using CSS And JQuery

Simple Modal Window Using CSS and jQuery

Simple Modal Window Using CSS and jQuery


In this tutorial, I’m going to share how to create a simple attractive light weight modal window with jQuery and CSS. I like jQuery, because it makes everything so simple and so easy.

You can view the working demo here.

Right, let’s start, this example will show you how to create a modal window that will display the content of a DIV using its #ID.

For jQuery, please include jQuery file in your page where you want to use this model window.

1. HTML code

# <!-- #dialog is the id of a DIV defined in the code below -->
# <a name="modalwindow" href="#open">Open</a>
#
<div>
#
#     <!--You easily customize your window here -->
#
<div class="window">
#         <strong>Testing of Modal Window</strong> |
#
#         <!-- close button is defined as close window -->
#         <a class="close" href="#">Close window</a>
#
#</div>
#
#     <!-- Do not remove div#hide, because you shall need it to fill the whole screen -->
#
#</div>

2. CSS code

 
# /* Z-index of #hide must lower than #container .window */
# #hide {
#   position:absolute;
#   z-index:9000;
#   background-color:#000;
#   display:none;
# }
#
# #container .window {
#   position:absolute;
#   width:440px;
#   height:200px;
#   display:none;
#   z-index:9999;
#   padding:20px;
# }
#
#
# /* Customize your modal window here, you can add background image too */
# #container #openbox {
#   width:375px;
#   height:203px;
# }

3. Jquery code

# $(document).ready(function() {
#
#     //select all the a tag with name equal to modalwindow
#     $('a[name=modalwindow]').click(function(e) {
#         //Cancel the link behavior
#         e.preventDefault();
#         //Get the A tag
#         var id = $(this).attr('href');
#
#         //Get the screen height and width
#         var hideHeight = $(document).height();
#         var hideWidth = $(window).width();
#
#         //Set heigth and width to hide to fill up the whole screen
#         $('#hide').css({'width':hideWidth,'height':hideHeight});
#
#         //transition effect
#         $('#hide').fadeIn(1000);
#         $('#hide').fadeTo("slow",0.8);
#
#         //Get the window height and width
#         var winH = $(window).height();
#         var winW = $(window).width();
#
#         //Set the popup window to center
#         $(id).css('top',  winH/2-$(id).height()/2);
#         $(id).css('left', winW/2-$(id).width()/2);
#
#         //transition effect
#         $(id).fadeIn(2000);
#
#     });
#
#     //if close button is clicked
#     $('.window .close').click(function (e) {
#         //Cancel the link behavior
#         e.preventDefault();
#         $('#hide, .window').hide();
#     });
#
#     //if hide is clicked
#     $('#hide').click(function () {
#         $(this).hide();
#         $('.window').hide();
#     });
#
# });
#

, ,

2 Comments


Create an action confirm form using “confirm_form()” function in Drupal

Doctor's List with delete option

Doctor's List with delete option


Action confirm form in Drupal

Action confirm form in Drupal

We can easily create an action confirm form using confirm_form() function in Drupal. Normally we need this form when user want to delete something and we want user to confirm his/her action. I am showing here an example in which we are listing all the Doctors information with Edit and Delete option. When user click the delete link we will show him the action confirm form with “Delete” and “Cancel” options. If user click the “Delete” button we will delete that Doctor record from database and if user click on “Cancel” we simply show the doctors list again.

Here is the code. I am using the module name “doctor” in this example.

Step 1. First implement hook_menu() to register new path in Drupal.

function doctor_menu() {
  $items = array();
 
  $items['doctors'] = array(
    'title' => t('Doctors'),
    'page callback' => 'doctors_list',
    'access arguments' => array('access doctor'),
    'type' => MENU_CALLBACK,
  );
 
  $items['doctors/delete/%doctor_user'] = array(
    'title' => t('Delete doctor'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('doctor_delete_confirm', 2),
    'access arguments' => array('access doctor'),
    'type' => MENU_CALLBACK,
  );
 
  return $items;
}

Step 2. Implementing the doctors_list() function to display the list of doctors.

function doctors_list() {
	$header = array(t('Doctor Name'), t('Gender'), t('Phone No.'), t('Status'), t('Action'));
 
	$query = "SELECT * FROM {doctor}";
	$rs = db_query($query);
 
	$row = array();
 
	if ($rs) {
		while ($data = db_fetch_object($rs)) {
			$gender = $data->gender == 'M' ? t('Male') : t('Female');
			$status = $doctor->status ? t('active') : t('inactive');
			$row[] = array(stripslashes($data->firstname) . ' ' . stripslashes($data->lastname), $gender, stripslashes($data->phoneno), $status, 
			"<a href='/doctors/edit/{$data->doctorid}'>" . t('Edit') . "</a> | <a href='/doctors/delete/{$data->doctorid}'>" . t('Delete') . "</a>");
		}
	}
 
	$str .= theme_table($header, $row);
 
	return $str;
}

Step 3. Create a wildcard loader function doctor_user_load() which we used in “doctors/delete/%doctor_user” path. This function checks the given “ID” in path is valid or not. If the given doctor id is not exists in database then “Page not found.” message will display.

function doctor_user_load($doctorid) {
	$query = "SELECT * FROM {doctor} WHERE doctorid = %d";
	$rs = db_query($query, $doctorid);
 
	if ($rs) {
		while ($data = db_fetch_object($rs)) {
			return $data;
		}
	}
 
	return FALSE;
}

Step 4. Create the doctor_delete_confirm() function. We are using the “confirm_form()” function in this function to show action confirm form.

function doctor_delete_confirm(&$form_state, $doctor) {
	$form['_doctor'] = array(
		'#type' => 'value',
		'#value' => $doctor,
	);
 
	return confirm_form($form,
    	t('Are you sure you want to delete this doctor?'),
    	isset($_GET['destination']) ? $_GET['destination'] : "doctors",
    	t('This action cannot be undone.'),
    	t('Delete'),
    	t('Cancel'));
}

Step 5. Create the Form API submit function for doctor_delete_confirm form.

function doctor_delete_confirm_submit($form, &$form_state) {
	$form_values = $form_state['values'];
 
	if ($form_state['values']['confirm']) {
		$doctor = $form_state['values']['_doctor'];
 
		doctor_delete($form_state['values'], $doctor->doctorid);			
 
		drupal_set_message(t('Doctor has been deleted successfully.'));
  	}
 
	drupal_goto("doctors");
}

, ,

14 Comments


Use lynx to run php file in crontab manager

Today, I was trying to set a php script file in crontab on Godaddy Virtual Dedicated server. Crontab executing that PHP script with warning. Actually, its not including the files which I am including using ‘require_once()‘ function. I have used the relative path for all the included files and its not possible to me to give absolute path for all files which are included. So, to solve this problem I have used lynx.

LYNX – lynx is the command line browser which is available on almost all the Linux versions. For more detail click here.

Instead, of using this command

/usr/bin/php /html/abc/public_html/cron.php

I have used this command

/usr/bin/lynx -source http://www.mywebsite.com/cron.php

in crontab manager. So, what lynx did is Its opens my cron.php files when this cron job execute.

-source Outputs HTML source instead of formatted text. To see all the available options of lunx click here.

If you don’t know the path of lynx on your server you can use ”whereis lynx” command using SSH. It will give you path of lynx directory on your server.

, ,

No Comments


Show image when its completely received by browser

Click on Image to see demo

Click on Image to see demo

See demo here

In this example, I am showing how to display image when its completely received by browser. We need this kind of thing when we are changing any Image through JavaScript and want to show some loader until image is not completely receive by client browser. I am using Image onload event for this purpose. Its fires when image is load by browser. When user click on prev or next link we hide the image by adding the ‘hide‘ class to ‘<img>‘. So, user will see the loader image which we placed in the background of image container. When browser load the next image we removed the ‘hide‘ class from ‘<img>‘ and changed its ‘src‘ from older image to new image. I am also using jQuery for adding and removing CSS class from HTML Element. Check out the Javascript, CSS and HTML code below.

HTML Code:-

<div class="container">
    <div class="prev"><a id="prev" href="javascript:void(0);">&laquo;Prev</a></div>
    <div class="image-container"><img id="pic" src="img/blank.jpg" class="hide" /></div>
    <div class="next"><a id="next" href="javascript:void(0);">Next&raquo;</a></div>
    <div class="clear-float"></div>
</div>

CSS Code:-

<style type="text/css" media="screen">
* {
	margin:0; padding:0; border:0;
	font-family:Arial, Helvetica, sans-serif;
	font-size:1em; font-weight:normal;
	font-style:normal; text-decoration:none;
	color:#666;
}
.container {
	width:800px;
	margin-left:auto; margin-right:auto;
}
.image-container {
	height:300px; width:400px; border:#333333 thin dashed;
	margin-top:100px;
	background:url(img/indicator2.gif) center no-repeat;
	float:left;
}
.image-container img {	height:300px; width:400px; }
.prev{
	width:50px;
	float:left;
	margin-left:143px;
	margin-top:250px; 
}
.next{
	width:50px;
	float:left;
	margin-top:250px;
	text-align:right; 
}
.clear-float {	clear:both; height:1px;}
.hide {	display:none;}
</style>

JavaScript Code:-

<script type="text/javascript" src="img/jquery.js"></script>
<script language="javascript">
	$(document).ready(function() {
		var index = 0; var path = 'img/';
		var images = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg"];
		var pre_images = new Array();
		var loaded = new Array();
 
		$("#prev").click(function() {
			index--;
			$("#pic").addClass('hide');
			if (index < 0) {index = images.length - 1}
			getImage();
		});	
 
		$("#next").click(function() {
			index++;
			$("#pic").addClass('hide');
			if (index >= images.length) {index = 0}
			getImage();
		});	
 
		function getImage() {
			if (loaded[index] == true) {
				document.getElementById("pic").src = pre_images[index].src;
				$("#pic").removeClass('hide');
			}
			else {
				pre_images[index] = new Image();
				pre_images[index].src = path + images[index];
				pre_images[index].onload = function() { 
					loaded[index] = true;
					document.getElementById("pic").src = pre_images[index].src;
					$("#pic").removeClass('hide');
				}
			}
		}
 
		getImage();
	});
</script>

, ,

1 Comment