Tricky Sql Statements

April 30th, 2009

Here are some tricky Sql statements that can be used in some specific cases. I figured them out in certain cases where I needed to do data manipulation directly on the database instead of writing script to accomplish them. I will describe them in case study style.

Case 1:

In one of my project there is a user table containing fields like userId, UserName, UserLoginID, Password etc. The UserLoginID field is basically the email address. Almost 95% of the email addresses belongs to a specific domain that is the domain of the project. Let’s say testproject.com. The table contains approx 12,000 records. In that project client decided to shift their main tld from .com to .org like testproject.com to testproject.org. Now they asked me to change the all the users’ email from .com to .org. That means user1@testproject.com to user1@testproject.org I needed to do this job within a shortest span of time. So I decided to run a sql command directly in the database to do the modification. A simple UPDATE sql won’t work in that situation as I needed to change some part of a field and also update statement shouldn’t affect those rows which do not contain testproject.com. So I tried with different types of update sql to do the job but finally derived the following one :-

UPDATE tblUser SET UserLoginID = REPLACE(UserLoginID, ' testproject.org', ' testproject.com');

The beauty of this statement lies in the usage of replace function. This replace function will synchronously select records having ‘testproject.com’ implementing functionality of the Where clause and generate the value to be set for the field UserLoginID as @testproject.org

Case 2:

This case was relatively easy. I need to find out unique entries from a table. It was not a hard job for me but still I googled a bit for this purpose. Now after some study I come to a position where I could do that using two different sql statements. They are :-

SELECT product_code FROM tblproductdetails GROUP BY product_code;

and

SELECT DISTINCT product_code FROM tblproductdetails;

While looking at the results I found both of them produces same result but the only differnce is Select DISTINCT does not sort the result set like GROUP BY does. So I wasn’t sure which one should used. SELECT DISTINCT vs GROUP BY - udbug | Google Groups helped me to chose the correct statement as Select DISTINCT. So I used the following :-

SELECT DISTINCT product_code FROM tblproductdetails ORDER BY product_code

Case 3:

This is also related with the earlier case of unique entries. This time I need to find out the ids which have duplicate entries. Almost the opposite job than the previous one. Well this statement also uses distinct but along with Group by clause gives the entries which have duplicates in the table. Here is the statement.

SELECT DISTINCT regn_id from tblstudentdetails group by regn_id HAVING count(regn_id) > 1;

This statement is very useful to find out entries which have duplicates in the tables.

Somebody asked me earlier how do I learn php and database? My answer was - learn the basic, find some real-life project to work for, take the challenge to complete it. You would face lots and lots problem while doing that. Don’t try to get rid of them but try to solve them. When you would finish the job you will understand the difference in you in terms of practical knowledge. I hope you all agree with me. :)

Picasa web album slideshow - Development guide

March 31st, 2009

I was looking for a application to embed slideshow using pictures from picase web album. I found some plugins which can be used in blog or myspace. Some of them uses the picasa slide show url opened in a iframe or div. Then you will have less control on the slideshow as it is controlled by the slideshow application of picasa. But I required more control on the images from picasa.

I was looking for some application which will fetch/store all the images for an album in picasa and create a slideshow with more control on the images. I found nothing thats suites my requirement. So I started to design an application of such kind. On the basis of functionality I sub devided it into two major part. First is fetch the image related information for an album and store it if required. Second is display the slideshow using those image information.

In picasa you can view the pictures as set or individual but you won’t get actual picture name or its location. So I found now simple way to get the pictures name and their location. While searching more for such option I found there is a RSS feed for each album. The RSS feed provides image names and its location details. It makes my job easier. Now objective became to process the RSS feed to get the image related information. For this purpose I used XML-RSS package from PEAR. Here is snapshot of the code I wrote to process the feed:


<?php
require_once "XML/RSS.php";
//$FeedURL is the URL of the rss feed of an album in picasa
$FeedURL = "http://picasaweb.google.com/data/feed/base/user/wce/albumid/5331321673727336541?alt=rss&kind=photo&hl=en_GB";
$rss =& new XML_RSS($FeedURL);
$rss->parse();
$rssArray = $rss->getStructure();
$PicasaDataArray = array();
$InfoArray = array();
for($C=0; $C<count($rssArray); $C++)
{
if($rssArray[$C]['type'] == ‘item’)
{
$PicasaDataArray[] = array(
‘title’ => $rssArray[$C]['title'],
‘image’ => $rssArray[$C]['enclosures'][0]['url'],
‘link’ => $rssArray[$C]['link'],
‘description’ => $rssArray[$C]['description'],
);
}
elseif($rssArray[$C]['type'] == ‘image’)
{
$AlbumTitle = $rssArray[$C]['title'];
$AlbumPicture = $rssArray[$C]['url'];
$CreateDate = $MetaInfo['lastbuilddate'];
}
}
// this $PicasaDataArray contains all the picture related information of an album from picasa web.
?>

Now this $PicasaDataArray can be stored in files/database or can be directly used for the slideshow. While processing the feed by this I found the feed contain other information like title, description, link of the album, its last build date etc. So I modified the code a little more to store these information too. So the first part of my application is complete.

Now the second part - slideshow using $PicasaDataArray. For this section I didn’t tried to put my head to develop slide show application as I had already seen some very nice attractive slideshow application. They are also easy to use and configure. One of my favourite is Lightbox JS. Another good slideshow script is Highslide. Both of them are very nice and easy to configure. So I used one of them for my purpose. Here is another snapshot of code


<?php
require_once "XML/RSS.php";
//$FeedURL is the URL of the rss feed of an album in picasa
$FeedURL = "http://picasaweb.google.com/data/feed/base/user/wce/albumid/5331321673727336541?alt=rss&kind=photo&hl=en_GB";
$rss =& new XML_RSS($FeedURL);
$rss->parse();
$rssArray = $rss->getStructure();
$PicasaDataArray = array();
$InfoArray = array();
for($C=0; $C<count($rssArray); $C++)
{
if($rssArray[$C]['type'] == ‘item’)
{
$PicasaDataArray[] = array(
‘title’ => $rssArray[$C]['title'],
‘image’ => $rssArray[$C]['enclosures'][0]['url'],
‘link’ => $rssArray[$C]['link'],
‘description’ => $rssArray[$C]['description'],
);
}
elseif($rssArray[$C]['type'] == ‘image’)
{
$AlbumTitle = $rssArray[$C]['title'];
$AlbumPicture = $rssArray[$C]['url'];
$CreateDate = $MetaInfo['lastbuilddate'];
}
}
?>
<html>
<head>
<title>Slide Show :: <?php echo $AlbumTitle;?></title>
<script type=”text/javascript” src=”js/prototype.js”></script>
<script type=”text/javascript” src=”js/scriptaculous.js?load=effects,builder”></script>
<script type=”text/javascript” src=”js/lightbox.js”></script>
<link rel=”stylesheet” href=”css/lightbox.css” type=”text/css” media=”screen” />
</head>
<body>
<a href=”<?php echo $AlbumPicture;?>” rel=”lightbox[picasa]“><img src=”<?php echo $AlbumPicture;?>” /></a>
<div style=”display:box;”>
<?php
foreach($PicasaDataArray as $ImageInfo)
{
echo ‘<a href=”‘.$ImageInfo['image'].’”‘ rel=”lightbox[picasa]“>’.$ImageInfo['title'].’</a><br> ‘;
}
?>
</div>
</body>
</html>

I made this code simple and easy to use. Though I have used xml-rss class from pear but it can be repalced by and standard xml-rss parser class. Experienced developer can modify this code or enhance its feature much more as per their requirement. If like to use this code or if you have any suggestion let me know about it via your comment.

Liquid Column Display Layout - Part II

February 9th, 2009

In my earlier post I had discussed about the designing the liquid 3 column display layout. While developing the structure I had some problem with the column heights. Depending upon the contents length of those columns varies. I have declared the height property as auto in the css. I could have declared them with some specific pixel value to make the columns of equal length. But if you consider your pages to contain dynamic content generated by server side scripting then this technique may fail. Particularly in Internet Explorer the data part may be extended beyond the columns, which could make the structure awful. So I was in need to find some other solutions for that purpose.

I thought of using some JavaScript to make all the columns height equal. The algorithm to do this is very simple. Calculate the max height among three columns and assign it for all the columns. So first I introduced three different IDs for these three columns to access the properties of those columns using Javascript document.getElementById() method. So I changed the HTML code as follows:


<div class="container">
<div class="contentDiv" id="contentDiv">
<div class="contentDiv_left" id="contentDiv_left"><img class="LcolImgDiv" src="../images/c2.jpg" border="0" alt="" /></div>
<div class="contentDiv_mid" id="contentDiv_mid">
<div class="hD1">Header Text</div>
<div class="hD2">Header text 2</div>
<p class="hD3">The text….</p>
</div>
<div class="contentDiv_right" id="contentDiv_right">
<ul>
<li><a class="item1" href="director/index.html">DIRECTOR SPEAKS </a> <img src="../images/bullet1.gif" alt="" vspace="0" /></li>
<li><a class="item1" href="students/index.html">STUDENTS </a> <img src="../images/bullet1.gif" alt="" vspace="2" /></li>
<li><a class="item1" href="alumni/index.html">ALUMNI </a> <img src="../images/bullet1.gif" alt="" vspace="2" /></li>
</ul>
</div>
</div>
<div class="footerDiv">
<div class="footerDivText">Copyright text</div>
</div>
</div>

contentDiv_left for the left column, contentDiv_mid for the middle column and contentDiv_right for the right one. contentDiv ID for the container div for these 3 columns.

Then my job was to find out the maximum height of these 3 columns. First I used offsetHeight property for this purpose. Calculate the max height and assign it to all the 3 columns style.height property. While testing the code I found it was working fine with Internet Explorer. In case of FireFox or Opera or Netscape browsers the code was malfunctioning, more specifically it was unable to find out the height of those columns using offsetHeight property. So I started looking for bug. While doing that I found out offsetHeight is a readonly property of the DHTML Object model introduced by MSIE. But is not part of any W3C specification or technical recommendation. So incase of browsers like FF or Opera it won’t work. So I started looking for some alternate property to find out the heights of those columns. There are some properties which didn’t worked for me are element.style.height, element.style.max-height etc. I tried with
window.getComputedStyle(element,null).getPropertyValue(”height”).
As window.getComputedStyle method can be used to get the styles of an element that are not set using the style attribute or with JavaScript. But it didn’t work too. Finally I worked out with this method :
document.defaultView.getComputedStyle(element, null).getPropertyValue(”height”).
The document.defaultView returns a reference to the default AbstractView for the document. This document.defaultView is part of the DOM Level 2 DocumentView interface. This interface is not a mandatory part of Document Object Model Level 2 Core specification. DOM of IE doesn’t implement this but DOM in mozilla supports this. So I put a browser check and utilized the above method for browser like FF, Opera and offsetHeight propery for IE. Hence my code looks like this :


function checkBrowserComponent() {
var ua = navigator.userAgent.toLowerCase();
if(ua.indexOf('msie')!=-1) {
return "ie";
}
else if(ua.indexOf('firefox')!=-1) {
return "ff";
}
return "oth";
}
function maintainMaxColHeight() {
var defMaxHeight = 400;
var elmMain = document.getElementById("contentDiv");
var elmLS = document.getElementById("contentDiv_leftSingle");
var elmL = document.getElementById("contentDiv_left");
var elmM = document.getElementById("contentDiv_mid");
var elmR = document.getElementById("contentDiv_right");
var ua = checkBrowserComponent();
if(ua == 'ff') {
if(elmLS != null) {
var lh = document.defaultView.getComputedStyle(elmLS, null).getPropertyValue("height");
lh = parseInt(lh);
if(lh > defMaxHeight) {
defMaxHeight = lh;
}
}
else {
var lh = document.defaultView.getComputedStyle(elmL, null).getPropertyValue("height");
lh = parseInt(lh);
if(lh > defMaxHeight) {
defMaxHeight = lh;
}
var mh = document.defaultView.getComputedStyle(elmM, null).getPropertyValue("height");
mh = parseInt(mh);
if(mh > defMaxHeight) {
defMaxHeight = mh;
}
}
var rh = document.defaultView.getComputedStyle(elmR, null).getPropertyValue("height");
rh = parseInt(rh);
if(rh > defMaxHeight) {
defMaxHeight = rh;
}
}
else if(ua == 'ie') {
if(elmLS != null) {
var lh = elmLS.offsetHeight;
if(lh > defMaxHeight) {
defMaxHeight = lh;
}
}
else {
var lh = elmL.offsetHeight;
if(lh > defMaxHeight) {
defMaxHeight = lh;
}
var mh = elmM.offsetHeight;
if(mh > defMaxHeight) {
defMaxHeight = mh;
}
}
var rh = elmR.offsetHeight;
if(rh > defMaxHeight) {
defMaxHeight = rh;
}
}
if(elmLS != null) {
elmLS.style.height = defMaxHeight+"px";
}
else {
elmL.style.height = defMaxHeight+"px";
elmM.style.height = defMaxHeight+"px";
}
elmR.style.height = defMaxHeight+"px";
elmMain.style.height = defMaxHeight+"px";
}

I called this function maintainMaxColHeight() in onLoad within body tag.

After adding this script the page now looks like :

3 equal cols liquid layout

Now what’s the conclusion? I think in case of maintaining the equal height for the columns there are 2 options. First one is to put a fixed pixel value as height property in css for all the columns. Next one is implementing this JavaScript code. For this second option browser should support JavaScript (I believe most of the current browsers do so). In my opinion if a website is designed using liquid column display layout where all pages contain static information, first option will the best for that case. I always prefer to avoid unnecessary script execution for web pages as it reduces the page download and display time. The second option is best for websites containing dynamic information (like my project).

The project where I have implemented this layout is near to completion. Still it is not fully online I won’t be able to show you. I need to wait a little more to show you the live example.

Coffee experience

January 15th, 2009

I used to think myself as a coffee lover. I like tea and coffee either with or without milk. But my favorite is black coffee. Many people don’t like black coffee due to its bitter taste and I liked it for the same reason. Due to the reason easy to prepare, I take most of the branded instant coffee. Last week I had gone to a well known branded coffee shop in shopping mall with my friend. We were coming back to office after a client meeting and my friend suggested me to have a good coffee treat after the meeting. There we had a tempting experience which put me in a dilemma of continuing my love for coffee.

After we entered into the coffee shop waiter showed us a table to seat and presented the menu (like a weekly magazine). Without wasting our time by going through it we ordered two Espresso for us. I had Americano earlier and so I thought Espresso is something like that. After few minutes waiter served us our order. I  was little curious while looking at the items, 2 small cups containing 4-5 sips of dark black concentrated coffee along with small paper packs of sugar and few cookies. The quantity of coffee was quite low but I was impressed with the aroma coming from them. So I put little sugar which was colored brown from the pack, mixed it with a spoon and made myself prepared to have a great experience of coffee. I just sipped a little and spontaneously OMG came out from my mouth. It was so concentrated and so bitter I ever had. It seemed to me like I some horrible medicine. I was trying to have it as quickly as possible but it seemed to like one of the toughest jobs I ever had. Both of us were almost speechless while completing our cups. We paid the bill, came out of the shop. Form a nearby grocery shop we bought bottle of drinking water and almost emptied them. Then we took a car and rush back to our office. Rest of the day we were cherishing about the coffee we had.

Coffee - Espresso

Coffee - Espresso

Today I find out some good resource about coffee. I learned a lot about coffee and it’s ordering options. Now I am sure I won’t order Espresso, may be I will go for Espresso Macchiato or Flat White or Cappuccino or may be Caffé Mocha. I request to all the reader who likes coffee but have less knowledge about it please read Coffee Drinks Illustrated or similar kind of stuffs before you go for a coffee break.

Liquid Column Display Layout

January 7th, 2009

I was busy with some of my projects. Few months back I was interested in liquid column layout structure. I had used this kind of layout in one of my project. This time I am going to discuss about the features of liquid column layout.

Earlier web page designing was highly dependent on HTML table structure. Common practice was to design a web page using HTML tags like table, tr, th, td, tbody etc. Web page designer used to design a layout in a graphic editor like Adobe Photoshop and slice the layout in small images in gif or jpeg format. Then create a table structure and insert those small images in different cells. This technique is very useful because putting those small rectangular images into different table cells, a web page can be designed having the same look and feel as layout image drawn in graphic editor. If not wrong till today this is the mostly used methodology to design web pages.

Let us review this designing procedure. I have described it in a very simplest way. Sometime designing a web page using the table structure based on graphical layout becomes a difficult job. If the graphical layout contains curves, color gradient then the complexity increases. I consider the most crucial part in this process is to design the table structure. Many times designer uses nested tables while designing the pages. Merging cells and rows are also widely used. Another important factor is how to put images in the table cells. Most of the cases img HTML tag is used, but sometimes inserting image as background works wonderfully.

So unless you don’t have a good knowledge of HTML table structure you won’t be able to work as professional web designer. In my early days in this profession I had to suffer with the complexity of nested table structure while designing pages.

In recent years I found there is a trend to avoid this procedure of designing web pages. There are certain reasons behind this change. First and foremost reason I think the size of the web page. Using nested table structure increases the file size of the web page, but many times it becomes unavoidable. I have also noticed a peculiar case of Internet Explorer while opening a page containing nested table. If the web page contains heavy images and huge text in nested tables, browser’s status will show “Done” while display of the page is not complete. IE shows “Done” status when display of the outermost table is complete. Another reason, editing the table structure in those web pages is quite difficult, that’s why people like to avoid this procedure. I found many times editing that kind of pages make the complex table structure incorrect. Support for other HTML tags having boxed or blocked like display such as div, layer, iframe etc by most of the browser is another important reason. Increasing use of CSS for applying style to provide a good look is also important. I found designer uses div tag supported with CSS instead of table to design web pages. They have produces pages which looks same as page designed using table structure and most importantly they have able to reduce the file size a bit.
Layouts like liquid column display, clean structure are the outcome of this increasing usage of div like tag instead of table tags in HTML. Though this new methodology is not very easy but I found there is a rapid increase in number who follows this.

Now here are the reasons why I was interested to implement liquid column display layout in one of my project.

  • If I need to design those web pages using table structure, I need to use one outermost table containing 3 columns. Now to display contents like (text, photographs), I need to use nested tables in those columns. I knew that I was going to suffer with that particular problem in IE. Also my file size will be higher.
  • There was another designing constrain that I can’t avoid using table structure. There was a background image that I had to display in the bottom portion of the page. Table structure wasn’t allowing me to do that.
  • The other reasons are basically the advantages of using liquid column display. I don’t like to discuss it here. You can always search to know about it. Let me discuss how do I designed the page layout.

Here is a sketch diagram about the structure that I was going to implement. It contains three columns which aligned in center and below footer. The page should display centered align three columns along with white spaces in the left and right side of the page. To design this structure I have used mainly div tags along with proper styles defined in CSS.

Here is a structural overview of the HTML code in the web page.


<div class="container">
<div class="contentDiv">
<div class="contentDiv_left"><img class="LcolImgDiv" src="../images/c2.jpg" border="0" alt="" /></div>
<div class="contentDiv_mid">
<div class="hD1">Header Text</div>
<div class="hD2">Header text 2</div>
<p class="hD3">The text….</p>
</div>
<div class="contentDiv_right">
<ul>
<li><a class="item1" href="director/index.html">DIRECTOR SPEAKS </a> <img src="../images/bullet1.gif" alt="" vspace="0" /></li>
<li><a class="item1" href="students/index.html">STUDENTS </a> <img src="../images/bullet1.gif" alt="" vspace="2" /></li>
<li><a class="item1" href="alumni/index.html">ALUMNI </a> <img src="../images/bullet1.gif" alt="" vspace="2" /></li>
</ul>
</div>
</div>
<div class="footerDiv">
<div class="footerDivText">Copyright text</div>
</div>
</div>

Here is styles defined in css


.container {
margin: 0px auto; width: 927px; padding:0px; border:0px;
}
.contentDiv {
height: auto; width:925px; padding:2px 2px 2px 2px; margin-top:5px; background:#F9E6EC; border:0px;
}
.contentDiv_left {
padding: 0px 0px 0px 0px; float: left; height: auto; width: 35%; background-image:url(../../images/column_bg.gif); background-repeat:repeat-y; border:0px;
}
.contentDiv_right {
padding: 0px 0px 0px 0px; float: right; height: auto; width: 28%; background-image:url(../../images/right_column_bg.gif); background-repeat:repeat-y; border:0px;
}
.contentDiv_mid {
padding: 0px 0px 0px 0px; float: left; height: auto; width: 35%; background:#FFC6E2; margin-left:10px; background-image:url(../../images/column_bg.gif); background-repeat:repeat-y; border:0px;
}
.footerDiv {
height: 20px; width:925px; padding:0px 2px 2px 2px; margin-top:5px; margin-bottom:10px; background:#AD5B66; border:0px;
}

Now here is outcome of the effort.

A brief explanation about the structure.
To design the 3 column structure I have used nested div tags with proper styles. There is a outermost div tag having class name contentDiv. Within that I have put 3 more divs with class names as contentDiv_left, contentDiv_mid and contentDiv_right. For these 3 divs I have defined float property in CSS and width in percentage value to achieve liquidity. For all those divs I have used height property as auto in CSS. This helps div to grow in lenght depending upon the content put in it.

Though I have implemented the 3 column liquid layout, there is a problem in it. If you look at the above picture you can spot out the problem. Yehh, the three columns are not of equal height. Depending upon the content added in those columns, their lengths will get adjusted. This is due to height:auto; in CSS for the 3 inner divs. One solution is to specify a big value as height in CSS. Pages will be unnecessarily long containing small content in those divs. Will create another problem.

I have used a technique to overcome this problem. I will be discussing it in my next post and this time next post I will do very soon. Till then comments, suggestions and queries are always welcome.

Welcome 2009

January 1st, 2009

Warm session greeting to all my friends, family members, co-workers, well wishers, supporters and last but wish to be least - spammers. Wish you all a very Happy New Year 2009 :)

Converting Excel date/time to Unix timestamp

August 29th, 2008

Timestamp conversion are required when you import information generated by Windows based application to UNIX system. I faced a similar type of problem when I was trying to read data from a MS Excel file and storing it in MySQL database using a php code.

I was using Excel_reader class to read the Excel file. In that file there were two columns for 2 dates. While reading those column value I found they contain some numeric value. Those values are not same as unix timestamp value. As I was trying to store those values as timestamp I need to convert them into the timestamp.

After some searching and reading from internet I found that Windows and Unix system stores timestamp in different manner. Once this is clear to me I have converted them easily. So let us understand how these two system stores timestamp .

In Unix system timestamp is stored as integer in terms of seconds. If we consider the current timestamp value in Unix then it is basically the no. of seconds passed from 1 January 1970 00.00Hrs to till now. One important thing for Unix timestamp is that it is measured with reference to GMT time. That means there is no time-zone adjustment considered in case of Unix timestamp.

In case of Windows time it is stored as floating point/real number but in terms of days. For current timestamp, the no. days spent from 1 January 1900 stored in integer part and fraction of the day stored in the fractional part of the timestamp.

Now comes the conversion process. I made a simple conversion calculation as follows:


$DayDifference = 25569; //Day difference between 1 January 1900 to 1 January 1970
$Day2Seconds = 86400; // no. of seconds in a day
$ExcelTime //integer value stored in the Excel column
$UnixTime = ($ExcelTime - $DayDifference)*$Day2Seconds;

Now if you look at the calculation, you may find that the conversion is not absolutely accurate. This is because I haven’t consider the fractional part of the Excel time. The reason behind doing so is that all I need to do is to convert a date from Windows format to Unix format. So fraction part of windows time won’t affect a lot for my requirement. But if you use this calculation for converting a date-time from Windows format to Unix format then conversion of the fractional part should done.
If you like this small tips please let me know about it.

I got my new logo

August 27th, 2008

For me its a celebration time! Wanna know why ?

Well I got my new logo for my website and company. At first take a look at it.

WCE Logo

Designed by my friend Nilkamal. Before he start working on it he asked me a simple question.

Do you dream about it?

I said yes. After 2 days this is the outcome. Simple but caries the senses. I like this guy, not because he is my friend but because of his artistic senses. I also love his professionalism. Together we had lot discussions related to art, culture, trends in visualization jobs and many more. Some day I will try to take his interview and then post it here.

** This is a long waiting post, as I was very busy with my jobs. Also I found some problem with my blog, which needed fresh installation. So I upgrade it with current version and make this post live.

QuickForm and Jscalendar

July 8th, 2008

Most of us are familiar with calendars in web pages. Small calendar showing date and year are really good to see and useful too. While in case of forms we have seen calendars attached with date fields. In some of my earlier projects I have designed date fields using simple drop down menu containing the data, month and year menu. It’s good but not very user friendly as user need to select 3 menus to choose a certain date. I had to stick with that format as I mostly use PEAR HTML_QuickForm to design forms in the web pages. Among many reasons the most unavoidable one is that it automatically generates client side validation JavaScript code. With time I realized that I should find some options to integrate calendar object with the QuickForm.

After giving a thorough search I selected jscalendar to incorporate with my form elements. The reasons behind selecting jscalendar are:

  • It has a nice interface and wide variety of themes.
  • Multiple integration options along with selectable date format to put the date in the text field.
  • Support for integrating the calendar object with HTML_QuickForm.

Prior to integrate the jscalendar I need to upgrade HTML_QuickFom version to 3.2.10 as I found some code added in this version to support jscalendar. I also need to upgrade my PEAR DB package to version 1.7.13 and DB_Table to version 1.5.5. In my projects most of the cases I generate forms using DB_Table instead of using QuickForm directly. This gives an extra benefit for data validation and storing them in database.

After the up-gradating the required pear packages I worked upon integrating the jscalendar code. After a spending a moderate amount of time I was able to work jscalender with the QuickForm. But unfortunately when I was trying generate forms using DB_Table jscalendar component was not working. I was getting javascript errors.
I was following the method described by Philippe Jausions of 11abacus in jscalendar.php file. It was working fine with the QuickForm. In that case I was using addElements function to add jscalendar with proper options using the $option array like this –


$options = array(
'baseURL' => '../js/jscalendar/',
'styleCss' => 'calendar-win2k-1.css',
'language' => 'en',
'button' => '',
'setup' => array(
'inputField' => 'datefield1',
'ifFormat' => '%d.%m.%Y %H:%M',
'showsTime' => true,
'time24' => true,
'weekNumbers' => false,
'showOthers' => true
),
);
$form->addElement('jscalendar', ' datefield1', 'My Date', $options);

I used this same option array in the column definition for the same field, as DB_Table uses the column definition for the attributes of the form elements of the form. I written like


'datefield1' => array(
'type' => 'varchar',
'size' => 20,
'qf_type' => 'jscalendar',
'qf_label'=> '<span class="caption">Date:</span>',
'require' => false,
'qf_attrs' => array('class'=> 'formfield','id' => 'datefield1'),
'qf_opts' => array(
'baseURL' => '../js/jscalendar/',
'styleCss' => 'calendar-win2k-1.css',
'language' => 'en',
'button' => '',
'setup' => array(
'inputField' => 'listadata',
'ifFormat' => '%d.%m.%Y %H:%M',
'showsTime' => true,
'time24' => true,
'weekNumbers' => false,
'showOthers' => true
),
),
'qf_client'=> true,
'qf_rules' => array(
'required' => 'Date is required.',
),
),

It didn’t worked and also gave the javascript error as calendar.Setup - no such method found….
Now I started working on how to fix this problem. I started checking the all the codes thoroughly and found that using QuickForm from DB_Table setting all these options can’t be done. After spending some upon those codes I rewrite the column definition like this


'datefield1' => array(
'type' => 'varchar',
'size' => 20,
'qf_type' => 'jscalendar',
'qf_label'=> '<span class="caption">Date:</span>',
'require' => false,
'qf_attrs' => array('class'=> 'formfield','id' => 'datefield1'),
'qf_opts' => array(
'ifFormat' => '%d.%m.%Y',
'showsTime' => false,
'time24' => false,
'weekNumbers' => false,
'showOthers' => false,
'button' => '',
),
'qf_client'=> true,
'qf_rules' => array(
'required' => 'Date is required.',
),
),

Also I declared the global path defining variable in the page where I was generating the form. I defined


$GLOBALS['_HTML_QUICKFORM_JSCALENDAR_BASEPATH'] = “/js/jscalendar/”;

Oh that time it worked. It showed the small calendar while the clicking the small button beside the text field for data. But I wasn’t still happy with it. What I found that the calendar was coming but it wasn’t using any style and dates are raveling upon a transparent layer, making it too ugly. I tried to define the style using style class/ stylesheet file name in different places as different parameter. But nothing worked. Now I had two options then

Define the stylesheet for the calendar within the head tags of the page containing the form, means hardcode the name of the stylesheet.
Change the coding to accommodate to options for setting the style class for the calendar.

Selecting the 1st option means loosing some dynamicity and selecting the 2nd option means I need to change or modify certain code in pear class package files. So it was difficult to select any option. I was investigating the benefits and the hitches which can come out as a result of using any one of those options. Also side by side I was looking for third other option which can be better then these two. I spent almost two days and came up with a decision of selecting the second option. I decided to add two lines of code in the QuicfForm.php file in the DB package as


if(isset($col['qf_theme'])) {
$element->theme = $col['qf_theme'];
}

Also I have added one more element in column definitions for the date field as


'datefield1' => array(
…… …….
…… …….
'qf_theme' => 'calendar-win2k-2',
),

Now my problem is solved and the jscalendar is working seamlessly with the QuickForm from the DB_Table package too.

My opinion is if you like to add the two lines of code in QuickForm.php file you can add it but you need to remember it at the time when you upgrade the pear package. Also you need to check if it works properly or not. The other way is to hardcode the stylesheet file within the head tag part of the page where you will go to generate the form. In this case you will surely loose some dynamicity but this is easier to work with. Choice is yours.

Currently I am working upon another important issue in php. I need some time to accomplish this job. I will discuss this issue too cause I find it very interesting. However if you find this above discussion useful then I might expect your comment here. Suggestion and queries are also welcome.

My favorite

June 26th, 2008

I am still searching theme for my blog. While doing so an idea came in to my mind. I must list my favorite movies in my blog. I have posted them in one of my earlier blog. Here I am cherishing them again.

First one is all about a battle. You might have seen this. If not watch it here. I’m sure you will like.

This is the 2nd highest viewed movie in YouTube . It almost near to 13.5 million views in YouTube. BBC has already reported this as fast biggest web video hits. Though its a amateur video but it is becoming the envy of professional wildlife snappers. The movie has got a professional quality script which many film director like to work with, but in reality there was no script! Its a battle between survivor(calf), paladins(group of buffalo), hero of land (lions) and owner of water(crocodile). The eight-minute-long footage shows nothing can be unachievable. Enjoy the The battle of Kruger ..
Some raw facts about battle of Kruger :

  • Place : a watering hole near Pretoriuskop Camp, Mpumalanga in South Africa’s Kruger National Park
  • Time : September 2004
  • Shooter : David Budzinski acconpanied by Jason Schlosberg
  • Submitted to Youtube : May 03, 2007

Now, a comment from Budzinski

“I’m not a camera person. I’m just lucky to have it!”

The second favorite movie is about time. Do you agree that sometimes each minute in our life becomes very important, vital or say crucial to our life? I’m pretty sure you will surely agree with me after watching this movie.

Some facts :

  • Its named as Just 10 minutes
  • Made by Ahmed Imamovic
  • The film won the award for the best European short film in 2002

I hope you like them both. I will come up with some php related issue in my next post very soon. Till then :)