Join Problems with Zend_Paginator and Zend_Db_Select objects

Zend_Paginator is one of the newest members of Zend framework family. It’s surely a rich addition with Zend’s power. Moreover, It’s handling the main data of pagination, not only pagination links. Which I didn’t found in any other pagination library.

But, when I (and many other developers) start to working with this library, found many problems/bugs. The matter is, they are being solved very fast and hope to get a bullet-proof pagination library soon. For example, here is tow important fixings about Zend_Paginator and Zend_Db_Table_Select.

I had to face a problem with Zend_Paginator when using Join in Zend_Db_Select object. I am explaining here how the problem arises and how to solve it.

The Problem

One of the 4 Adapters for Zend_Paginator is DbSelect which uses a Zend_Db_Select instance. Now, the problem occurred if I need to have some calculative data from other tables and use join with the Zend_Db_Select object for them. For example, I am retrieving data from `deals` table and collecting number of comments from `comments` table and total votes from `votes` table. So, with other conditions, I had to add this lines with select object:

   1: $select->joinLeft(array('c' => 'comments'), 'deals.id = c.deal_id', array('total_comments'=> 'count(c.id)') );
   2: $select->joinLeft(array('v' => 'votes'),    'delas.id = v.deal_id', array('total_votes'   => 'count(v.id)') );
   3: $select->group($this->_name . '.id');

 

Now, the Zend_Paginator will always calculate the TotalRows as 1. That means, $this->totalItemCount; will always print 1 in “view partial“.

Why it happens?

Let’s take a look to the count function of DbSelect Adaptor of Zend_Paginator:

   1: public function count()
   2: {
   3:     if ($this->_rowCount === null) {
   4:         $expression = new Zend_Db_Expr('COUNT(*) AS ' . self::ROW_COUNT_COLUMN);
   5:         
   6:         $rowCount   = clone $this->_select;
   7:         $rowCount->reset(Zend_Db_Select::COLUMNS)
   8:                  ->reset(Zend_Db_Select::ORDER)
   9:                  ->reset(Zend_Db_Select::LIMIT_OFFSET)
  10:                  ->columns($expression);
  11:                  
  12:         $this->setRowCount($rowCount);
  13:     }
  14:  
  15:     return $this->_rowCount;
  16: }

Here, at line 7, the column list is being removed. But we have a `Group By` clause in our select object which is not cleared by this function and the result is always 1. At this point, if we add “->reset(Zend_Db_Select::GROUP)” after line 9, the calculation will get rid from always being 1. But there will arise another problem. That is, joined tables are still remaining in `From` clause. You can see them by adding “die(print_r($rowCount->getPart(Zend_Db_Select::FROM)));” after line 10. This join tables will make the calculation inconsistence because there is no expression columns now to summarize their result.

The Solution

Just alter this function as following to prevent this problem:

   1: public function count()
   2: {
   3:     if ($this->_rowCount === null) {
   4:         $expression = new Zend_Db_Expr('COUNT(*) AS ' . self::ROW_COUNT_COLUMN);
   5:        
   6:         $rowCount   = clone $this->_select;
   7:         $rowCount->reset(Zend_Db_Select::FROM);
   8:         
   9:         foreach($this->_select->getPart(Zend_Db_Select::FROM) as $name => $table)
  10:         {
  11:             if(empty($table['joinCondition']))        
  12:             {
  13:                 $rowCount->from(array($name => $table['tableName']));
  14:             }
  15:             elseif($table['joinType'] == 'inner join')        
  16:
       {
  17:                 $rowCount->join(array($name => $table['tableName']), $table['joinCondition']);
  18:             }
  19:         }
  20:         
  21:         $rowCount->reset(Zend_Db_Select::COLUMNS)
  22:                  ->reset(Zend_Db_Select::ORDER)
  23:                  ->reset(Zend_Db_Select::GROUP)
  24:                  ->reset(Zend_Db_Select::LIMIT_OFFSET)
  25:                  ->columns($expression);
  26:  
  27:         $this->setRowCount($rowCount);
  28:     }
  29:  
  30:     return $this->_rowCount;
  31: }

At line 9, I am running a foreach which will remove the `from` clause and again assign only the main table and inner join tables. And, at line 23, just removing the `Group By` clause from query. Now, this function will provide right calculation even when there is some joins like this. But, if you use inner join in your Zend_Db_Select object (which is very rare for pagination), this function may not serve properly.

If there is any mistake in this alternation or any other way can make it better, please let me know. And… let’s meet power with simplicity.

UPDATE [26/08/08] : The function is updated and hopefully it will work fine for inner joins too.

UPDATE [24/09/08] : This issue is solved in ZF 1.6. Jurrien Stutterheim has reported about this post in Zend Framework Issue tracker and worked on it. After the release of 1.6, he requested me to check if this issue still exist. I’ve checked and found it solved. Thanks to Jurriën Stutterheim.

My Bookmarks – A WordPress plugin to show your valuable bookmarks on sidebar

If you are using delicious or simpy as your bookmarking tool, this plugin is for you. This will help a wordpress user to show his valuable bookmarks on sidebar. Just install this plugin and set your options in plugins settings page – you are done. When you add or update links on your bookmarking site, this section will be automatically updated.

my_bookmarks

The settings page of My Bookmarks in wordpress admin panel

Download

Click here to download the My Bookmarks WordPress plugin (80.3 KB).

Downloaded : [downloadcounter(my_bookmarks)] times

To see a live demo, see the “My Bookmarks” section of sidebar of this blog.

Installation

Installation of this plugin is very easy. First, be sure that you are using latest(2.6) version of wordpress. Then follow this 3 easy steps.

  1. Extract and upload the `MyBookmarks` directory to the `/wp-content/plugins/` directory.
  2. Activate the plugin through the Plugins menu in WordPress.
  3. Go to Settings > My Bookmarks page and make it yours.

Upcoming features

I’ve planned to add some more feature in next version of this plugin. Your comment about any modification or feature request is very mush welcome.

  1. Add caching to store link information in your server. So that, no need to fetch from feeds every time.
  2. Allow more bookmark sites like digg, netvouz, etc.
  3. Adding additional links with parsed feed.
  4. Make independent about enabling blogroll.
  5. ……….. and more.

For any Question/Suggestion please contact me at admin@ajaxray.com

Happy bookmarking, Happy blogging!

Developing web application with PHP-MySql-Apache in Ubuntu Linux

I have started using Ubuntu 8.04 in few days ago and found it Great. So, now I’ve moved my development environment from windows and working in Ubuntu. Here I am just explaining what steps I had to take for this jump. Also have a listing of some development related softwares/tools which I am using as replacement of windows applications.

Installing Apache, Php5, MySql in Ubuntu:

You can install Apache, Php, Mysql and other applications from Synaptic Package Manager. Go to System > Administration > Synaptic Package Manager and search with your desired application name. When found, double-click on package name. The package will be marked for installation along with it’s dependences. Now click on apply button to install the package. In this post, the red+bold texts are the name of software package which can be installed from Synaptic Package Manager.

To make your system ready for PHP development, you have to install more or less this packages: apache2.2-common, apache2-utils, php5, mysql-server-5.0, mysql-client-5.0, mysql-query-browser etc. You may also require some common php extensions which may not installed automatically with PHP installation. Most of them also will be found in Synaptic Package Manager as php5-gd, php5-curl, php5-mysql, php-pear etc.

Paths of important directories

One of the major differences I find here is the file system. All the directory paths I’ve been using in windows are changed here. I m listing here some PHP-MySql related paths here. But they may differ on your installation.

  • Apache configation files: /etc/apache2/
  • localhost root directory: /var/www/
  • PHP ini file: /etc/php5/apache2/
  • PHP extensions configuration files : /etc/php5/conf.d
  • MySql Data files: /var/lib/mysql/mysql
  • MySql Configuration files: /etc/mysql/

PHP Editors for Ubuntu

Gedit is the default text editor of Ubuntu and it support syntax coloring for many languages including PHP. But If you want an advanced editor for programming, you can try Geany or Screem. But, I am sure, who’ve been using advanced IDEs like PHPEd or PHPDesigner in windows, none of this can satisfy him. Don’t worry, the great open source IDE eclips has PHP-Development-Tool. It’s surely one of the best PHP IDE.

Subversion in Ubuntu

Subversion maintains current and historical versions of source code and documentation. It’s very important for distributed application development. RapidSVN is a graphical client for the subversion revision control system (svn) for linux. If you want to use svn from command line, install subversion.

File Difference and Merging Tools for Ubuntu

I have been using WinMerge in windows as file comparison and merging tool along with TortoiseSVN. Now using TkDiff as it’s alternative in linux. TkDiff has advanced functionalities and graphical interface. It provides file-merge and change-summary facilities, line number toggling (for easier cut & paste) and support for Subversion, RCS, CVS and SCCS. To use from command line, diff is may be the simplest file comparison tool.

Ftp and SSH

Ubuntu installs its default programs for FTP, SSH and many other internet applications. But, I’ve liked gFTP as FTP application because of it’s interface is similar to SmartFTP. And for working with SSH, required nothing. Just open the terminal and use ssh command. Write something like ssh username@example.com and press ENTER.

Testing in IE

One of the important (and painful to me) issue of web development is testing the output in IE. Though IE has no version for Linux, you can install it through wine. Wine is a application that crates a virtual environment for installing windows applications in Linux. After installing wine, you can install any available version of IE from http://www.tatanka.com.br/ies4linux/page/Installation:Ubuntu.

When witting this post, my aim was to help a developer who is thinking to switch to Ubuntu Linux or a newcomer here. You are welcome to add your valuable comment/suggestion for the same purpose.

PHP Universal Feed Parser – lightweight PHP class for parsing RSS and ATOM feeds.

After the PHP Universal Feed Generator, I’ve written the PHP Universal Feed Parser for Orchid Framework. It’s a RSS and ATOM parser written in PHP5. Though there are many feed parsers over Internet, none of those was serving the basic focuses of Orchid: pure object orientation, being lightweight etc. So, I had to write a new one.

UPDATE(15th May, 2008) : cURL support added. Where url fopen() is disabled, the class will use cURL to load the RSS/ATOM content.

Features:

  • Parses all channels and feed item tags and sub tags.
  • Serve the parsed data as associative array.
  • Enough documented and easy to understand code.
  • Many ways to get parsed information.
  • Parsing includes attributes too.
  • No regular expression used.
  • Parsed by XML Parser extension of PHP.
  • Pure PHP5 objected oriented.
  • Enable to parse all commonly used feed versions.

Supported versions: I tried to include all stable and commonly used feed versions. Currently it’s being used to parse the following versions:

  • RSS 1.0
  • RSS 2.0
  • ATOM 1.0

Download:

  • Click Here to get the class file with example. (downloaded [downloadcounter(feedparser)] times)
  • Download from phpclasses.org.

How to use:

It’s dead simple to use this class. Just follow this 3 steps:

1. Include the file

include(‘FeedParser.php’);

2. Create an object of FeedParser class

$Parser = new FeedParser();

3. Parse the URL you want to featch

$Parser->parse(‘http://www.sitepoint.com/rss.php’);

Done.

Now you can use this functions to get various information of parsed feed:

  • $Parser->getChannels() – To get all channel elements as array
  • $Parser->getItems() – To get all feed elements as array
  • $Parser->getChannel($name) – To get a channel element by name
  • $Parser->getItem($index) – To get a feed element as array by it’s index
  • $Parser->getTotalItems() – To get the number of total feed elements
  • $Parser->getFeedVersion() – To get the detected version of parsed feed
  • $Parser->getParsedUrl() – To get the parsed feed URL

A simple example:

Here is a simple example of using this Feed Parser class. Click here to see is the output of this example.

<?php
include('FeedParser.php');
$Parser     = new FeedParser();
$Parser->parse('http://www.sitepoint.com/rss.php');

$channels   = $Parser->getChannels();
$items      = $Parser->getItems();
?>
<h1 id="title"><a href="<?php echo $channels['LINK']; ?>"><?php echo $channels['TITLE']; ?></a></h1>
<p id="description"><?php echo $channels['DESCRIPTION']; ?> </p>

<?php foreach($items as $item): ?>

    <a class="feed-title" href="<?php echo $item['LINK']; ?>"><?php echo $item['TITLE']; ?></a>
    <p class="feed-description"><?php echo $item['DESCRIPTION']; ?></p>
<?php endforeach;?>

I hope, this class is so easy that, anyone who have general knowledge about PHP5 can use it. Whatever it is, Feel free to ask me anything, anytime.


Note : Hi all, I’ve reported about some situations from users where this class is not working properly. So, I’ve decided to re-write it ASAP. Hope the next one will be more powerful, smaller in size and easier to use.
— Thanks.

PHP Universal Feed Generator (supports RSS 1.0, RSS 2.0 and ATOM)

It’s been a while since I’ve planned on developing a RSS writer that fulfills most my needs by supporting the various feed formats. Although the necessity was the prime force behind it, a discussion with Hasin and Emran has put the actual fire in. We were discussing about what can be added next in the Orchid – “PHP framework for the rest of us” and suddenly it hit me. At last, it’s finally complete and I’ve named it “PHP Universal Feed Generator“, as it generates both ATOM and RSS feeds.

Supported versions:

  • RSS 1.0 (which officially obsoleted RSS 0.90)
  • RSS 2.0 (which officially obsoleted RSS 0.91, 0.92, 0.93 and 0.94)
  • ATOM 1.0

Download:

Features:

  • Generates RSS 1.0, RSS 2.0 and ATOM 1.0 feeds
  • All feeds are are validated by feed validator.
  • Supports all possible feed elements.
  • Simple and easy to define channel and feed items
  • Implements appropriate namespaces for different versions.
  • Automatically converts date formats.
  • Generates UUID for ATOM feeds.
  • Enables usage of subtags and attributes. (example: image and encloser tags)
  • Completely Object oriented in PHP5 class structure.
  • Handles CDATA encoding for required tags.
  • Nearly same code for generating all kinds of feed

A minimum example

It’s a minimum example of using this class. I am generating a RSS 2.0 feed from retrieved data from a MySQL database. There are more examples in the download package for different versions.

<?php
  // This is a minimum example of using the Universal Feed Generator Class
  include("FeedWriter.php");

  //Creating an instance of FeedWriter class. 
  $TestFeed = new FeedWriter(RSS2);

  //Setting the channel elements
  //Use wrapper functions for common channel elements
  $TestFeed->setTitle('Testing & Checking the RSS writer class');
  $TestFeed->setLink('http://ajaxray.com/projects/rss');
  $TestFeed->setDescription('This is test of creating a RSS 2.0 feed Universal Feed Writer');

  //Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
  $TestFeed->setImage('Testing the RSS writer class','http://ajaxray.com/projects/rss','http://www.rightbrainsolution.com/images/logo.gif');

    //Retriving informations from database
    mysql_connect("server", "mysql_user", "mysql_password");
    mysql_select_db("my_database");

$result = mysql_query(“Your query here”);

 

    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        //Create an empty FeedItem
        $newItem = $TestFeed->createNewItem();

        //Add elements to the feed item    
        $newItem->setTitle($row['title']);
        $newItem->setLink($row['link']);
        $newItem->setDate($row['create_date']);
        $newItem->setDescription($row['description']);

        //Now add the feed item
        $TestFeed->addItem($newItem);
    }

  //OK. Everything is done. Now genarate the feed.
  $TestFeed->genarateFeed();
?>

Shhhh….a universal feed reader is on the way 😉

PHP UUID generator function

Universally Unique Identifier is an identifier standard which is used in a varieties of software construction. When I was writing the RSS Writer class for Orchid, I needed to generate UUID to implement with ATOM id. I searched the web for a simple solution but didn’t find any that suffices my need. Then I wrote the following function to generate it. I’ve use the standard of canonical format here.

Let’s take a look what Wikipedia has to say about the format of UUID :

A UUID is a 16-byte (128-bit) number. The number of theoretically possible UUIDs is therefore 216*8 = 2128 = 25616 or about 3.4 × 1038. This means that 1 trillion UUIDs would have to be created every nanosecond for 10 billion years to exhaust the number of UUIDs.

In its canonical form, a UUID consists of 32 hexadecimal digits, displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters.

Enough said 🙂 Here is the function.

/**
  * Generates an UUID
  *
  * @author     Anis uddin Ahmad
  * @param      string  an optional prefix
  * @return     string  the formatted uuid
  */
function uuid($prefix = '')
{
    $chars = md5(uniqid(mt_rand(), true));
    $parts = [substr($chars,0,8), substr($chars,8,4), substr($chars,12,4), substr($chars,16,4), substr($chars,20,12)];

    return $prefix . implode($parts, '-');;
}

Example of using the function –

//Using without prefix.
//Returns like: 1225c695-cfb8-4ebb-aaaa-80da344e8352
echo uuid();

//Using with prefix
//Returns like: urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344e8352
echo uuid('urn:uuid:');

See you.

UPDATE : The PHP Universal Feed Generator class, for which I wrote this function is released.

UPDATE: The method of getting random string changed based on Davids comment. (Thanks to David)

UPDATE: Updated syntax. Made more concise using features of recent PHP versions.

How to avoid POSTDATA resend warning

"POSTDATA resend" warning is a common problem when developing web applications. Before discussing about the solution, let’s know what is the problem actually and when it arises.

About the problem :

We see this warning when we try to revisit a page that has accepted POSTDATA using browser’s history mechanism. Usually we do it by browser’s BACK button or refreshing a page. When a page in browser history requested with POST method, the browser thinks this POSTDATA is important to process this page. So, it asks the user if he wants to send the POSTDATA again or not. Different browsers show this warning differently. For example, the images below shows how Firefox and Internet Explorer show this warning.

POSTDATA_resend_mozilla

POSTDATA resend warning in Mozilla Firefox

POSTDATA_resend_ie

POSTDATA resend warning in Internet Explorer

 

Now, If the user accepts the confirmation, the page is reloaded with previously sent data using POST method; otherwise some browsers don’t take any action and some shows a "Webpage has expired" message. In some situations, this re-submitting is useful, but most of the times it’s not expected. It’s more harmful when user accepts it without understanding and causes multiple entries of previously entered data in database.

The easy solution :

The easy solution is simply redirecting. When we redirect a page, the target page is loaded without any POST data that comes with request.

Let’s solve this problem by hand. Say we have 2 pages – A and B. A has a feedback form which submits data by POST request method to B. B inserts the information into database and shows a success message.

Now, if the user try to reload the page by refresh, back button or any other way, browser will show the confirmation message. If user accepts this, the message will inserted again. But after inserting to database, If we redirect to another page C and C shows the success message, the problem will not occur. Because, in the final output to the browser will come from C which didn’t use any POST request data. The code should be something like this:

<?php
if($_POST)
{
  /* Form validation, Inserting to database or anything you want goes here */
  
  /* Now redirect to another page */
  header('Location: http://yoursite.com/success.php');
}
?>

 

Extending the solution :

The solution I explained above can show just an static message like "Thanks for your feedback" or "Registration completed successfully" etc. But usually we like to include some information about sender or submitted information in the success of failure message. For example:

Hi Andrew, your registration is successfully completed. An email is sent to you at andy001@yahoo.com with more information.

In the above message, the purple colored information has to be taken from POST data. But the POST data will be lost when redirecting. So, it’s not possible by the above solution.

What we can do to solve this is that we can use SESSION to store those data which we want to display with message in redirected page. Just like this:

<?php
session_start();
 
if($_POST)
{
  /* Form validatio, Inserting to database or anything you want goes here */
  
  //Store data to session
  $_SESSION['name']   = $_POST['name'];
  $_SESSION['email']  = $_POST['email'];
  
  //Now redirect to another page 
  header('Location: http://yoursite.com/success.php');
}
?>

 
In the target page, when showing the success message, we can get the information from SESSION easily.
 
Hope this will solve your problem. Please tell me if any confusion or question with this article.  See you again.

Interactive character limit for textarea using Jquery

For a textbox, character of a field can easily be limited with maxlength attribute. But maxlength doesn’t work for  a textarea. So, It needs an alternate way. For one of my project, I wrote a function for this purpose where I used jQuery. Here I am explaining how I did it.

Let’s look an example of this interactive solution here

OK. Now we will make this in 2 easy steps.

1. Import your jQuery file and write the function "limitChars(textid, limit, infodiv)" in the head section of your page.

This function takes 3 parameters. They are:

  • textid : (string) The ID of your textarea.
  • limit : (num) The number of character you allow to write.
  • infodiv : (string) The ID of a div, in which limit information will be shown .

  Here is the function:

 1: <script language="javascript" src="Jquery.js"></script>
 2: <script language="javascript">
 3: function limitChars(textid, limit, infodiv)
 4: {
 5: var text = $('#'+textid).val(); 
 6: var textlength = text.length;
 7: if(textlength > limit)
 8: {
 9: $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
 10: $('#'+textid).val(text.substr(0,limit));
 11: return false;
 12: }
 13: else
 14: {
 15: $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
 16: return true;
 17: }
 18: }
 19: </script>

Remember, the script is using jQuery. So be careful about the path of jquery at first line of this script.
 
2. Bind the function to the keyup event of your textarea. Do this in jQuery’s ready event of document. Just like this:
 1: $(function(){
 2: $('#comment').keyup(function(){
 3: limitChars('comment', 20, 'charlimitinfo');
 4: })
 5: });

Here my textarea’s id is ‘comment’ , limit of characters is 20 and limit information will shown in a div whose id is ‘charlimitinfo’. That’s all, we have made an "Interactive character limiter" for our textarea using Jquery.
 
If you are not using jQuery for your site, it will not be wise to include it only for this script. You can get the same functionality from javascript without jquery. Look at this example. It looks like and works 100% as the previous though not using jquery.
Here you need just 2 changes. First, change the function "limitChars" as follows :
 1: function limitChars(textarea, limit, infodiv)
 2: {
 3: var text = textarea.value; 
 4: var textlength = text.length;
 5: var info = document.getElementById(infodiv);
 6:  
 7: if(textlength > limit)
 8: {
 9: info.innerHTML = 'You cannot write more then '+limit+' characters!';
 10: textarea.value = text.substr(0,limit);
 11: return false;
 12: }
 13: else
 14: {
 15: info.innerHTML = 'You have '+ (limit - textlength) +' characters left.';
 16: return true;
 17: }
 18: }

 
And finally, call the function manually on keyup event of your textarea. Use "this" keyword for textarea instead of id when calling the function. example:
 1: <textarea name="comment" id="comment" onkeyup="limitChars(this, 20, 'charlimitinfo')">
 2: </textarea>

Finished. We made the solution again without dependency of any javascript framework.

Please let me know if you have an idea to make it better. 

jQuery controlled Dependent (or Cascading) Select List 2

Thank you all. Thanx for using, commenting and visiting my script jQuery controlled Dependent (or Cascading) Select List from my old bolg http://php4bd.wordpress.com and here.

I am getting a lots of request and questions from visitors about adding some features and some other problems. Sometimes I faced some problem when using this script myself. So, I have made some changes here. I hope, this change will help you to overcome some problems of previous version of this script. The main features added in this version are:

  1. It will keep in child list box only sub items of selected parent value when initializing.
  2. Added a 4th parameter to input a selected value for child list box.
  3. When "isSubselectOptional" is true, add a default value ‘none’ for ‘– Select –‘ option of child list box.
  4. Automatically focus the child list box when a value is selected from parent list box.
  5. More effective for multilevel association.

Click here to see a demo of multilevel association using this function. here is same demo for jquery 1.3.x users.

Here is the modified function (for < jquery 1.3):

 1: function makeSublist(parent,child,isSubselectOptional,childVal)
 2: {
 3: $("body").append("<select style='display:none' id='"+parent+child+"'></select>");
 4: $('#'+parent+child).html($("#"+child+" option"));
 5: 
 6: var parentValue = $('#'+parent).attr('value');
 7: $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
 8: 
 9: childVal = (typeof childVal == "undefined")? "" : childVal ;
 10: $("#"+child+' option[@value="'+ childVal +'"]').attr('selected','selected');
 11: 
 12: $('#'+parent).change( 
 13: function()
 14: {
 15: var parentValue = $('#'+parent).attr('value');
 16: $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
 17: if(isSubselectOptional) 
 18: $('#'+child).prepend("<option value='none'> -- Select -- </option>");
 19: $('#'+child).trigger("change"); 
 20: $('#'+child).focus();
 21: }
 22: );
 23: }

Again, here is the function for jquery 1.3.x. Thanks a lot to TuxX for tuning up it to work with jquery 1.3.x.

[javascript]
function makeSublist(parent,child,isSubselectOptional,childVal)
{
$("body").append("<select style=’display:none’ id=’"+parent+child+"’></select>");
$(‘#’+parent+child).html($("#"+child+" option"));

var parentValue = $(‘#’+parent).attr(‘value’);
$(‘#’+child).html($("#"+parent+child+" .sub_"+parentValue).clone());

childVal = (typeof childVal == "undefined")? "" : childVal ;
$("#"+child).val(childVal).attr(‘selected’,’selected’);

$(‘#’+parent).change(function(){
var parentValue = $(‘#’+parent).attr(‘value’);
$(‘#’+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
if(isSubselectOptional) $(‘#’+child).prepend("<option value=’none’ selected=’selected’> — Select — </option>");

$(‘#’+child).trigger("change");
$(‘#’+child).focus();
});
}
[/javascript]

And initialize the association on ‘$(document).ready’, as following example:

 1: $(document).ready(function()
 2: {
 3: makeSublist(’parentID’,'childID’, true, 'selected_val_of_child');
 4: });

If you want to create multilevel association, start the initialization from child most order. such as:

 1: $(document).ready(function()
 2: {
 3: makeSublist('child','grandson', true, ''); 
 4: makeSublist('parent','child', false, '3'); 
 5: });

For details instruction and example of using this script, please visit the previous version. Feel free to ask me if any problem with using this script or any bug you found.

UPDATE [09/10/09] : Updated function added for jquery 1.3.x

Ruby on Rails: Begin with the easiest tutorial

When I have been hearing a lot about Ruby and thinking to give it a try, I searched for a beginners tutorial over Internet. I found a lot. But luckily, I started with the easiest and solid one. It successfully drive me through an exciting way of learning ruby and lift me from installing to a functional "online cookbook" application. The best part of this tutorial was, it teach everything really "step by step" and you have to turn back to a previous step for never. 2 parts of this great tutorial is here –

part-1 : Rolling with Ruby on Rails

part-2 : Rolling with Ruby on Rails, Part 2

Ok. It’s confirming your successful starting. For the next step, I am listing here some essentials of learning Ruby on Rails.

  1. http://tryruby.hobix.com/ : This is an interactive interface for learning Ruby. They said,"Got 15 minutes? Give Ruby a shot right now!".
  2. What is ruby on Rails – This is another tutorial from http://www.onlamp.com/ describing amazing features of Ruby on Rails.
  3. Four Days on Rails (PDF) : This PDF goes through building a "To-Do List" Application. The steps of building a ruby applications are explained here excellently.
  4. http://wiki.rubyonrails.com/rails : Ruby on Rails Wiki : The community-driven Rails documentation! A place where you will get everything about Ruby on Rails.
  5. http://api.rubyonrails.com/ : The details documentation of Rails API.
  6. http://rubyforge.org/ and http://raa.ruby-lang.org/index.html: These are the world’s richest  collection of open source ruby project.
  7. Seeing is believing : Screencasts of Ruby on Rails application. Makes a programmer interested on Ruby on Rails in just 01 minute.
  8. Ajax on Rails : This is the 3rd part of the introducing tutorial. A must read to work with Ajax in Rails framework.