Sunday, January 23, 2011

CakePHP jquery autocomplete

Im using cakephp 1.2 and want to make autocomplete on them
Have googling for several hours (including tying it) and finally succeed

p/s: Im using try an error method. Im afraid that this 3rd try was success because of additional code I have put during try #1 and #2

1st I try to use this and succeess (except when want to autocomplete from database source)
Using original jquery http://jqueryui.com/demos/autocomplete/ which is version jquery-ui-1.8.8.custom.min.js and jquery-ui-1.8.8.custom.css

2nd was from this blog (this fail)
http://nuts-and-bolts-of-cakephp.com/2008/05/07/jquery-autocomplete-in-cakephp/
http://www.pengoworks.com/workshop/jquery/autocomplete.htm

3rd was from this website
http://www.cakephp.bee.pl/ajax/autoComplete

Thanks for all those programmer who make my life easier

After several investigation (I go crazy with these 2nd try for almost 2 days and turned out it cause of URL?)
I manage to enable the 2nd try. The reason of error is because I didnt put my system name
the website tutorial said "/products/autoComplete" but if your CakePHP 1.2 system name is 'accounting' means its going to become '/accounting/products/autoComplete'

What next? I want to make the view to be able to save more Account name. Thus is use a loop like this
input("Account.$aa.name"); ?>
input("Account.$aa.id"); ?>

Remember, the account name is just a name. At the controller what matters is the Account.$aa.id
Thus, after the autocomplete on the Account Name, the Account Id will be put the Id of the selective Account

To do this you require to modify function findValue(...) because this is where the event for 'Choosing which Account Name from the list of autocomplete'. And also a dummy input and one new function

New dummy input (on the view)
<input id="tempCount" value="" />

New dummy function (on the view at the javascript)
function tempCountert( theTempCountValue)
{
document.getElementById('tempCount').value = theTempCountValue;
}
Then you need to change you loop for the account name

From
input("Account.$aa.name"); ?>

To
input("Account.$aa.name", array( 'onchange'=>'tempCountert("Account'.$aa.'Id")')); ?>

Finally will be on the function findValue(li). Make sure to add this code
var updatedColumner = document.getElementById('tempCount').value;
document.getElementById(updatedColumner).value = sValue;



How my code works?
  1. You type in some value in the 'Account name' and the autocomplete list out the match
  2. When you click one of the match result. The dummy input (tempCount) will change the value to Account Name index. let say Account.0.name will print out 'Account0Id' in dummy input
  3. Function findValue(...) will be executed. And get the value in dummy input. Thus change the value

No comments: