Examples:
Default options:
<style>
.ac_results {
padding: 0px;
border: 1px solid black;
background-color: white;
overflow: hidden;
z-index: 99999;
color: black;
}
.ac_results ul {
width: 100%;
list-style-position: outside;
list-style: none;
padding: 0;
margin: 0;
}
.ac_results li {
margin: 0px;
padding: 2px 5px;
cursor: default;
display: block;
/*
if width will be 100% horizontal scrollbar will apear
when scroll mode will be used
*/
/*width: 100%;*/
font: menu;
font-size: 12px;
/*
it is very important, if line-height not setted or setted
in relative units scroll will be broken in firefox
*/
line-height: 16px;
overflow: hidden;
}
.ac_loading {
background: white url('indicator.gif') right center no-repeat;
}
.ac_odd {
background-color: #eee;
}
.ac_over {
background-color: #0A246A;
color: white;
}
</style>
<?php echo $form->create('User', array('url' => '/ajax/view')); ?>
<?php echo $ajax->autoComplete('Post.subject', '/ajax/autoComplete')?>
<?php echo $form->end('View Post')?>
Comments
Post a comment
Additional options:
- $options['var'] - name of variable that stores handler to autoComplete method
2010-04-04 13:42:36
Hi,
It would be very helpful if you show us the controller code and especially the autoComplete method of the ajax controller.
thanks
2010-04-05 19:35:32
Hi!
there is the code of autoc method (which is repsponsible for results in autocomplete):
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'Post.subject LIKE' => '%'.$this->params['url']['q'].'%'
),
'limit' => $this->params['url']['limit'],
'fields' => array('subject')
)));
$this->layout = 'ajax';
2010-04-19 17:51:07
could you please give an example of a view? As whenever I click on a result it puts the HTML (including the <li> and <a> tag) inside the input.
2010-04-19 22:16:36
Matthew Dunham:
jQuery autocomplete library that helper use for this method require data in plain text, separated with newline signs (\n) and it automagicly convert it to HTML with <b> tags.
Example:
<?foreach($posts as $post):?>
<?=$post['title']?>
<?endforeach?>
2010-04-22 23:24:46
Hi,
First of all, Great Helper.
I have a Question:
The autocomplete function can pass like an option the value of a diferent textbox than the textbox generated by the function. If the answer is yes, how I do that?
Thanks....
2010-04-23 17:11:49
gabrielr:
<script>
function paramss()
{
var out = {};
out['text'] = $('input[name="zzz"]').val(); //where zzz is name of your input
return out;
}
</script>
<?php echo $form->create('User', array('url' => '/ajax/view')); ?>
<?php echo $ajax->autoComplete('Post.subject', '/ajax/autoc', array('extraParams' => 'paramss()'))?>
<?php echo $form->end('View Post')?>
2010-04-24 04:31:55
thanks for answer !!!.
I wanna check it later
2010-04-26 21:19:09
About passing extra paramss in Autocomplete,
In the controller action how I use this Extra params, in the array $this->params or Where is it?
Thanks for help me..
2010-04-27 07:45:40
Hi gabrielr:
Lastly when I answered I made a little mistake and now I'm attaching correct example :)
<?php echo $form->create('User', array('url' => '/ajax/view')); ?>
<?php echo $ajax->autoComplete('Post.subject', '/ajax/autoc', array('extraParams' => '{extra: function() { var out = {}; out["title"] = $(\'[name="zzz"]\').val(); return out; }}'))?>
<?php echo $form->end('View Post')?>
in controller you can use extra params by $this->params['url']['extra']
2010-04-28 02:28:00
Thanks , it works now !!!
Great Helper
2010-05-04 20:07:33
How am i suppose to make the item works as a link instead of inserting text result to textbox?
2010-05-06 18:35:13
Hi Juidan!
This helper doesn't allow you to do this type of events, but you can try do it in jQuery like here: http://docs.jquery.com/Plugins/Autocomplete (at the bottom)
2010-05-08 00:04:44
thanks Kvas i've done that . it works great !
2010-05-11 21:37:11
People,
I click on a result it puts the HTML (including the <li> and <a> tag) inside the input.
mi view is:
<?php foreach($ruts as $rut): ?>
<?php echo $rut['Cliente']['rut_cliente']; ?>
<?php endforeach; ?>
2010-05-12 15:56:31
Mr_sangrin, maybe you have other version of autocomlete library?
2010-05-22 07:13:59
Hi,
I am trying to use the autocomplete with an array as the datasource. Can you show me what my autoComplete function in controller code should look like?
2010-05-23 12:33:02
Kevin Lambert, I think you shoul use:
$this->params['url']['key_name']
2010-05-23 16:23:01
ahh, thanks kvas!, that did the trick for me
2010-05-24 09:44:43
Very good, I love you so much!!!
2010-05-25 14:48:33
Hi, first of all let me start by saying thank you for such a wonderful helper. I am having some difficulty making it useful for my purposes though. My controller function is:function autoComplete() {
$this->set('subjects', $this->Subject->find('all', array(
'conditions' => array(
'Subject.name LIKE ' => '%'.$this->params['url']['q'].'%'
),
'limit' => $this->params['url']['limit'],
'fields' => array('name','id')
)));
$this->layout = 'ajax';
}
And in my autocomplete.ctp I have :
<?php
if(!empty($subjects))
{
foreach($subjects as $subject)
{
echo $subject['Subject']['name']. '|' .$subject['Subject']['id'] . "\n";
}
}
else
{
echo 'No results!'."\n";
}
?>
My difficulty is that, I can't seem to figure out how to save the id to the form instead of the name. How can I intercept that id value and set it as the form submit value? Thanks.
2010-05-25 15:46:44
Hi Samantha!
I think that you can use: 'formatResult' option...
Maybe something like this will help:
'formatResult' => 'return value.split("|")[1];'
2010-05-25 16:28:43
Hmm, this would work perfectly except I don't know the name of the returned object which contains the data :(. I looked at the API and came up with nothing.
2010-05-25 16:44:56
Ok, thanks again Kvas, your hint put me on the right track. What worked for me was this :
'formatResult' => 'return data[1];'
I hope this helps someone else who might be wanting to do something similar to myself. :)
2010-06-03 15:33:15
Hi! I have a really simple problem when using autoload and cant make it to work right.
When user types something in the text field, there's no list showing up, just raw text under the input field :( Please help.
The code :
### search.js - included in search view ###
$(document).ready(function() {
$('#showOthersPosts').click(function(){
$('#user_search_form').show();
});
});
### search.ctp view ###
<?php echo ($this->Html->script('jquery.autocomplete.min', false)); ?>
<?php echo ($this->Html->script('search', false)); ?>
<a href='javascript:;' id='showOthersPosts'>Show other's posts</a>|
<form id='user_search_form' style="display:none">
<fieldset>
<label for="UserUsername" class="postlabel"><span>User</span></label>
<?php echo $ajax->autoComplete('User.username','/users/show_usernames', array('class' => 'fullwidth'))?>
</fieldset>
</form>
### show_usernames.ctp view ###
<?php foreach($usernames as $username): ?>
<?php echo $username['User']['username']."\n"?>
<?php endforeach; ?>
What am I doing wrong?
2010-06-03 18:17:01
Nevermind my last post, im stupid:)
2010-06-09 23:27:05
Hi, thanks! Nice helper. I have a question, how can i associate the autocomplete method to a single input? like $form->input instead of echo $ajax->autocomplete. Sorry for my english...
2010-06-10 10:24:00
Hector, you can only use $ajax->autocomplete, but this method can get parameters as $form->input...
2010-08-30 23:26:26
Hello,
I have a problem, the results are not displayed.
My autocomplete.ctp :
$this->log($workoutplaces, LOG_DEBUG);
foreach($workoutplaces as $place):
echo $place['Workoutplace']['place'] ;
endforeach;
In the log file I can see my results but not on the web page ...
In witch it is supposed to be displayed ?
Thanks for your help.
2010-08-31 13:34:01
I've found the problem ... my view/layout/ajax.ctp was empty ...
with :
<?php echo $content_for_layout; ?>
it's ok !
2010-09-07 23:06:29
Hi dp35!
Great that you solve your problem :)
2010-09-29 06:35:32
Hey man, and validation?
2010-09-29 08:14:27
Hi lippert!
That for info about bug. Oryginal version of helper also do not provide validation. I've changed my helper and it's working now. You can download new version and update your ajax.php file.
2010-10-18 19:58:51
hey man i have, example full views and controllers, by guide?
2010-10-18 20:11:53
hey man you have some guidance or example complete with views and controllers, plus where you invoke the. js
2010-10-19 17:36:48
Hi obelksyavhe,
The view source is in the example code block. Controller that is responsible for autocomplete ajax response is in the 2nd comment.
What do you mean with 'invoke the. js'?
BTW this method works nearly like in oryginal Ajax Helper in CakePHP...
2010-10-29 19:53:29
Is there a way to paginate the result set ?
2010-10-30 10:02:54
Hi Ay Dot,
Autocomplete is not best tool for presenting lots of data, so there is no way to paginate.
You can try using better search methods in your controller to present better results at top...
2010-12-06 00:47:59
Is there a way to have an additional parameter with a value from another form field passed to the controller? I'm trying to restrict options presented in the autocomplete based on another form field. I tried using the extraParms option, but couldn't figure out how to set extraParms in javascript instead of in the view.
2010-12-06 22:01:53
Hi vm8,
You should try code from 6th comment (from 2010-04-23 17:11:49). I explained there how to use extraParams in javascript.
2011-01-02 23:10:39
Hi,
Looks like a nice tool, however I'm having some difficulties, it seems like it is using default.ctp in stead of ajax.ctp, any clue about the cause?
thanks!
2011-01-04 17:44:58
Hi Jerre,
You can try with $this->layout = 'ajax' in your controller.
2011-01-04 21:46:50
Thanks for your answer.
That's in it, but still gives the default.ctp
2011-01-05 16:32:34
Hi Jerre,
In my apps it's working fine.
Maybe you are inserting code in wrong action?
2011-01-06 23:02:06
If have the following in my controller:
function autoComplete() {
echo $this->params['url']['q'] . "---";
$this->loadModel("User");
$this->set('subjects', $this->User->find('all', array(
'conditions' => array(
'User.username LIKE ' => '%'.$this->params['url']['q'].'%'
),
'limit' => $this->params['url']['limit'],
'fields' => array('username')
)));
$this->layout = 'ajax';
}
2011-01-07 18:25:44
Hi Jerre,
Your code looks fine. Maybe you have modified ajax.ctp?
2011-01-07 20:13:38
content views/ajax.ctp:
<?php echo $content_for_layout; ?>
content of my page:
-- the CSS of the top --
<?php echo $form->create('Complaint', array('url' => '/ajax/view')); ?>
<?php echo $ajax->autoComplete('User.username', '/ajax/autoComplete')?>
<?php echo $form->end('View Post')?>
2011-01-20 18:27:37
with this code :
<?php foreach($articles as $a): ?>
<?php echo $a['Article']['nom']; ?>
<?php endforeach; ?>
it does not split the results into separate lines and when i click one article name in the list, just copies all the lines as one in the input field.
Any idea ?
2011-01-20 20:50:29
Hi William,
Do you have your results, every in one line?
If no you must break lines. If yes, you can post your ajax response here and then I'll try to help you.
2011-01-21 03:56:01
I have the result as :
Bonbons propolis eucalyptus 70gPropolis spray bio 30mlPropex 24mlGommes propolis orange<!-- 0.1s -->
instead of :
Bonbons propolis eucalyptus 70g
Propolis spray bio 30ml
Propex 24ml
Gommes propolis orange
<!-- 0.1s -->
2011-01-21 18:30:48
hi again William,
add "\n" after every article or add enter after echo.
2011-01-21 19:33:32
adding "\n" after every article leads to stopping the ajax request. I can't see any reason for it but without the "\n" every new letter you type, the script sends a request. With the "\n", there is only one request (output in firebug).
What do you mean by "add enter" ?
2011-01-22 07:33:07
By "add enter" I mean that you can add break line between echo and enfforeach.
But I still don't know what is wrong when you add "\n". This solution should work. Maybe chack what is your output then.
2011-01-22 09:20:29
Form :
echo $ajax->autoComplete('Article.nom', '/articles/autocomplete', array(
'label' => '',
'size' => 34,
'value' => 'rechercher',
'onclick' => 'erase(this)'
));
Controller :
function autocomplete() {
$this->set('articles', $this->Article->find('all', array(
'conditions' => array(
'Article.nom LIKE' => '%'.$this->params['url']['q'].'%'
),
'fields' => array('Article.nom'),
'limit' => $this->params['url']['limit']
)));
$this->layout = 'ajax';
}
view -> autocomplete.ctp :
<?php foreach($articles as $a): ?>
<?php echo $a['Article']['nom']; ?>
<?php endforeach; ?>
layout-> ajax.ctp :
<?php echo $content_for_layout; ?>
ajax output (without "\n") for 'prop':
Bonbons propolis eucalyptus 70gPropolis spray bio 30mlPropex 24mlGommes propolis orange<!-- 0.0988s -->
This should be :
Bonbons propolis eucalyptus 70g
Propolis spray bio 30ml
Propex 24ml
Gommes propolis orange
<!-- 0.0988s -->
As soon as I add the "\n" (like this : echo $a['Article']['nom']."\n";), the function only sends one request (for the first letter). So it collects only the first 10 results. Why does the addition of "\n" stop the process ?
2011-01-22 17:19:44
When you type 1 letter it should collect only 10 results, because its default limit of jquery autocomplete. But if you type 2nd character it should make 2nd request for new elements to show. If you want to get more items you should add parameter 'max' when you calling autocomplete method.
If javascript isn't making second request You should check what error is displayed in your firebug.
BTW this javascript library has enabled cache at default, so if you type the same chars again it won't make ajax request.
2011-01-22 20:33:39
This is the problem : when I type a second letter with "\n" in the autocomplete view, there is no second request so it does not find all the results.
Without this "\n" there is a second (and third and ...) request and all the matching items are found but they are on a single line.
No error is reported in firebug in either case.
2011-01-23 13:03:17
Hi William,
Maybe the problem is with this jquery lib and it isn't making secound request if all results from last response are matching your query...
2011-01-25 20:17:19
Thanks for this great library! I am trying to setup autocomplete for a foreign key. I have a CONTACTS table that has a COMPANY_ID field that references the COMPANIES table's ID field. I want to set it up so that instead of a drop down it is a text-field that the user starts to type in the company name. If it exists in the COMPANIES table it will show as autocomplete; however, if it doesn't it will add it to the COMPANIES table as a new record.
Thanks in advance!
2011-01-27 17:02:41
After a loooooooooooooooong time thinking about it, I finally found out where the problem was. This autocomplete does not work with debug set anything else than 0. So setting debug to 0 solved the problem.
Notice that autocomplete using Prototype works fine with debug set to 1 or 2.
2011-01-28 07:54:07
Hi William,
Great that you found a solution of this problem. And thanks for info for other users.
2011-02-01 17:04:05
Hi everybody,
It works well on IE, but it does not work on Firefox. Help me!!!
2011-02-01 18:39:57
Hi HaiNguyen,
Maybe you can read errors from your firebug?
2011-02-06 06:28:12
Hi kvas,
I used firebug. I enabled all panel. I typed some letters, such as "Tr". Then I view console/errors, but it has no any error. I view "All", in "response" display:
<script type="text/javascript" src="/thuchanh/js/prototype.js"></script><script type="text/javascript" src="/thuchanh/js/scriptaculous.js"></script><script type="text/javascript" src="/thuchanh/js/effects.js"></script><script type="text/javascript" src="/thuchanh/js/controls.js"></script>
<ul>
<li>Tran Phuc Hau</li>
<li>Tran Thuy Tien</li>
<li>Tran Thi My Xuyen</li>
</ul>
However, no list is displayed in my web page. Please, help me!!
2011-02-06 13:38:37
Hi HaiNguyen,
maybe problem is with fact that you include scripts in your view.
BTW, why you're using prototype with this helper?
2011-02-06 14:22:31
Hi kvas,
when I remove this script:
<script type="text/javascript" src="/thuchanh/js/prototype.js"></script>
I see it doesn't affect web page. I don't understand why it (autocomplete) doesn't work on FF?
2011-02-06 14:32:59
In my controller:
CanbosController, I have a function (use for autocomplete):
function autoComplete() {
$this->set('canbos', $this->Canbo->query('select distinct Canbo.hotencb from canbos as Canbo
where
Canbo.hotencb LIKE\''. $this->data['Canbo']['tim'].'%'.'\''
)
);
$this->layout = 'ajax';
}
In view/canbos, I created auto_complete.ctp:
<?php
echo $javascript->link('prototype');
echo $javascript->link('scriptaculous');
echo $javascript->link('effects');
echo $javascript->link('controls');
?>
<ul>
<?php foreach($canbos as $post): ?>
<li><?php echo $post['Canbo']['hotencb']; ?></li>
<?php endforeach; ?>
</ul>
I use autocomplete in view/canbos/index:
<div class="formsearch" style="float:right;background-color:#e8edff;">
<!--form id="TimSearchchForm" method="post" action="./tims/searchch"-->
<?php echo $form->create('Canbo', array('action'=>'search')); ?>
<table border="0" cellpadding="0">
<tr>
<td colspan="3" align="center"><font color="red">Nhập họ tên, (hoặc) mã số cán bộ, địa chỉ, email</font></td>
</tr>
<tr>
<td><b>Nội dung </b></td>
<td><?php echo $ajax->autoComplete('Canbo.tim', '/canbos/autoComplete')?></td>
<td><input type="submit" name="Submit" value="Tìm"></td>
</tr>
<tr>
<td> </td>
<td colspan="2" align="left"><input type="checkbox" name="data[Canbo][chinhxac]" value="1" id="TimChinhxac">tìm chính xác </td>
</tr>
</table>
</form>
</div>
I tried on IE, it works, FF doesn't.
2011-02-06 14:52:57
In my controller:
CanbosController, I have a function (use for autocomplete):
function autoComplete() {
$this->set('canbos', $this->Canbo->query('select distinct Canbo.hotencb from canbos as Canbo
where
Canbo.hotencb LIKE\''. $this->data['Canbo']['tim'].'%'.'\''
)
);
$this->layout = 'ajax';
}
In view/canbos, I created auto_complete.ctp:
<?php
echo $javascript->link('prototype');
echo $javascript->link('scriptaculous');
echo $javascript->link('effects');
echo $javascript->link('controls');
?>
<ul>
<?php foreach($canbos as $post): ?>
<li><?php echo $post['Canbo']['hotencb']; ?></li>
<?php endforeach; ?>
</ul>
I use autocomplete in view/canbos/index:
<div class="formsearch" style="float:right;background-color:#e8edff;">
<!--form id="TimSearchchForm" method="post" action="./tims/searchch"-->
<?php echo $form->create('Canbo', array('action'=>'search')); ?>
<table border="0" cellpadding="0">
<tr>
<td colspan="3" align="center"><font color="red">Nhập họ tên, (hoặc) mã số cán bộ, địa chỉ, email</font></td>
</tr>
<tr>
<td><b>Nội dung </b></td>
<td><?php echo $ajax->autoComplete('Canbo.tim', '/canbos/autoComplete')?></td>
<td><input type="submit" name="Submit" value="Tìm"></td>
</tr>
<tr>
<td> </td>
<td colspan="2" align="left"><input type="checkbox" name="data[Canbo][chinhxac]" value="1" id="TimChinhxac">tìm chính xác </td>
</tr>
</table>
</form>
</div>
I tried on IE, it works, FF doesn't.
2011-02-06 14:55:25
You should delete scripts from auto_complete.ctp at first and use only jquery.
If this doesn't help start debuging with firebug.
2011-02-06 15:17:46
Hi kvas,
Thank you very much!!
I removed those scripts (declaration of javascript) which are in header of auto_complete. As a result, it works!!
2011-02-07 13:00:09
Hi kvas,
Now, I want to create a search engine which likes GOOGLE. When I type some letter into search field, the results will display below immediately (same to autocomplete). How can I do?
2011-02-07 17:49:30
Hi again HaiNguyen,
I think that code in 2nd comment will help you.
2011-02-08 15:42:15
which one? Can you tell me where it is?
2011-02-08 15:53:53
Can you tell the way to use it?
2011-02-11 05:50:48
hi,
can you solve my issue which are i am facing when using autocomplete. issue is that when type single word then autocomplete populate result comes in single "li" not diffrent "li", but when i type second word after first it show correct.
my controller code is that
$this->set('locations', $this->Location->find('all', array(
'conditions' => array(
'Location.name LIKE' => '%'.$this->params['url']['q'].'%'
),
'fields' => array('name')
)));
$this->layout = 'ajax';
and autocomplete.ctp code is that
<?php foreach($locations as $location): ?>
<?php echo $location['Location']['name']; ?>
<?php endforeach; ?>
here is the code for calling
echo $ajax->autoComplete('Location.CustLocationId', '/locations/autoComplete');
please help me
2011-02-11 07:56:34
Hi hemendra,
Maybe you can look into your firebug and check what are the responses from server for both your requests?
I think that this can help with debugging...
2011-02-19 11:36:18
I'm having this issue where I have difficulties formatting the layout of the output:
Now I just get an almost invisible list of items (no background color for the dropdown, the items in it are white).
When I put HTML code in the auto_complete.ctp it's just printed as text.
When I add <font color="black"><?php echo $content_for_layout; ?></font> nothing changes.
Any idea how I can adjust this?
2011-02-19 12:52:31
Hi Jerre,
Did you included styles (into your view file where you're using ajax method) from example above?
2011-02-19 15:07:21
ok stupid of me, that did the trick!
Thanks!
2011-02-23 14:54:17
Hi, I tried get a object tool, but only get a string of tool's name.
My PostsController
function autoComplete()
//work it, only string name
'fields' => array('Post.name')
//don't work it, error in query
'fields' => array('Post.name', 'Post.id')
Could it be that the model I use $hasAndBelongsToMany?
2011-02-23 15:00:36
Sorry, tool change for post.
When a delete the var $hasAndBelongsToMany = array(..) in my Post Model, works it, but I am not convinced.
2011-02-24 13:36:45
Hi Pedro,
Try to check whats wrong in your model by creating normal action (not for ajax). In debug mode cake should tell you what is wrong.
2011-03-11 12:45:02
Hi,
Thanks for the helper, it works for me like a charm!
But i have a question. How i have to do for fill multiple's fields with this code?
I tried do it, but i'm doing samething wrong.
I write here my code, maybe you can help me...
controller:
function articulosAutoComplete(){
$this->set('articulos', $this->Articulo->find('all', array(
'conditions' => array(
'Articulo.articulo LIKE' => '%'.$this->params['url']['q'].'%'),'limit' => $this->params['url']['limit'])));
$this->layout = 'ajax';
}
auto_complete.ctp:
<ul>
<?php foreach($articulos as $articulo): ?>
<li onclick="EntradaDescArticulo.value = '<?php echo @$articulo['Articulo']['desc_articulo'];?>'">
<?php echo $articulo['Articulo']['articulo'];?></li>
<?php endforeach; ?>
</ul>
in my view:
echo $ajax->autocomplete('articulo', '/articulos/articulosAutoComplete', array( 'class' => 'inputclient', 'label' => 'Articulo'));
echo $form->input('desc_articulo', array('class' => 'inputstore', 'label' => 'Descripción'));
Just for a field works great, but for two not.
Please help me!
2011-03-14 08:45:36
Hi Jabit,
I've never tried something like this, so I can't help you...
2011-03-14 12:01:46
Hi kvas!
thanks for answering! but just I'm trying your Autocomplet code but filling multiple's fields.
If samebody know the answer or have a solution, please help me! tanks
2011-03-15 13:17:49
Hi Kvas!
I find the solution using prototype autocomplete...
here http://bakery.cakephp.org/articles/MartinLissmats/2010/03/12/autocomplete-multiple-fields
Thanks
2011-03-18 00:10:08
hi kvas
Thank you for sharing this helper lots of people find this very helpful.
I got and error on firebug
" $("#UserUsername").autocomplete is not a function
[Break On This Error] $('#UserUsername').autocomplete('/autocop/users/autoComplete', {}); "
and no result on browser.
My developement envi
cakephp1.3.7
FF
table names:users
fields:id, username
users/users_controller.php
<?php
class UsersController extends AppController {
var $helpers = array ('Html','Form','Javascript', 'Ajax');
var $name = 'Users';
var $layout = 'simple';
var $components = array('DebugKit.Toolbar');
function index() {
$this->set('users', $this->User->find('all'));
}
function add() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
}
}
}
function autoComplete() {
$this->set('users', $this->User->find('all', array(
'conditions' => array(
'User.username LIKE' => '%'.$this->params['url']['q'].'%'
),
'limit' => $this->params['url']['limit'],
'fields' => array('username')
)));
$this->layout = 'ajax';
}
}
?>
users.add.ctp
<?php echo $form->create('User', array('url' => '/users/view')); ?>
<?php echo $ajax->autoComplete('User.username', '/users/autoComplete')?>
<?php echo $form->end('View Post')?>
users/auto_complete.ctp
<?php foreach($users as $a): ?>
<?php echo $a['User']['username']; ?>
<?php endforeach; ?>
I followed your instruction on how to use this helper.maybe a miss something why i got this error.
thanks in advance for your help.
2011-03-19 08:46:23
Hi johny,
Are you sure that you have included link to autocomplete javascript in your layout?
2011-03-22 16:37:05
@kvas
thanks i forgot the autocomplete js on layout.
i have another problem on the list it add an extra value
example:
the result on firebug
den
dedo
deb
<!-- 0.6628s --><table class="cake-sql-log" id="cakeSqlLog_13008079754d88c1279e7704_06756596" summary="Cake SQL Log" cellspacing="0" border = "0">
<caption>(default) 2 queries took 5 ms</caption>
<thead>
<tr><th>Nr</th><th>Query</th><th>Error</th><th>Affected</th><th>Num. rows</th><th>Took (ms)</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>SELECT `User`.`id`, `User`.`password`</td>
</tr>
</table>
the table add on the list. how can i remove that table on the list.
2011-03-22 18:25:30
Hi johny,
Turn off debug mode and everything should be OK.
2011-03-23 04:13:32
@kvas
how to turn off? i'm using 1.2.3 bacause i'm modify an old application.
the helper works great using 1.3.7
thanks in advance.
2011-03-23 14:06:07
@kvas
Nevermind my post the helper working great on both 1.2.3 and 1.3.7 version on my application.
thanks a lot
2011-03-25 10:01:19
Hello I've a problem. I cannot create an autocomplete.
katalogs_controller:
function autoComplete() {
$this->set('katalogs', $this->Katalog->find('all', array(
'conditions' => array(
'Katalog.Haupteintrag LIKE' => '%'.$this->params['Katalog']['Haupteintrag'].'%'
),
'fields' => array('Haupteintrag'),
'group' => 'Haupteintrag'
)));
$this->layout = 'ajax';
}
add.ctp:
<td class="view_td">Hauptsortierung:</td>
<td><?php echo $form->input('HauptSort', array('label' => false));?></td>
can you help me?
thanks
2011-03-25 10:13:19
edit...
my add.ctp is:
<td class="view_td">Haupteintrag:</td>
<td><?php echo $ajax->autoComplete('Katalog.Haupteintrag', '/katalogs/autoComplete', array('label' => false));?></td>
2011-03-28 19:01:20
Hi basti,
Try:
function autoComplete() {
$this->set('katalogs', $this->Katalog->find('all', array(
'conditions' => array(
'Katalog.Haupteintrag LIKE' => '%'.$this->params['url']['q'].'%'
),
'fields' => array('Haupteintrag'),
'group' => 'Haupteintrag'
)));
$this->layout = 'ajax';
}
2011-04-21 06:32:10
hi kvas - this is great stuff. 2 questions:
1) When I have an habtm field, the for tries to create a multiple select field. I can overwrite the 'type' setting in the options to be 'text', but for some reason, your code is removing the 'type' entry in the options array (it gets unset in the __getHtmlOptions function via the $ajaxOptions array). Is that necessary? i removed 'type' from the $ajaxOptions and now it recognizes the text type and works properly, but not sure if that breaks other functions/features. Any other way to get that to work?
2) I haven't found any sample code on how to return both an id and a name (to use the name in the text field, but use the id for the value that gets submitted in the post). Is that possible? Any sample code available on how to do that?
3) Is it possible to implement the multiple autocomplete feature in jquery (see demo here: http://view.jquery.com/trunk/plugins/autocomplete/demo/ - the Multiple Birds example). Any reason this wouldn't work via your plugin?
Thanks again for great helper.
2011-04-21 18:53:38
Hi dan,
1) Method __getHtmlOptions removes params that are used in ajax request. Type decides that request is asynchronous/synchronous.
2) I've never tried something like this :)
3) I think that you can pass parameter 'multiple' => true and it'll work, but I haven't checked this.
2011-04-21 23:09:25
hi kvas - thanks for reply. On question #1 above, so there is a problem because type is used in the $form->input array as well as autocomplete. This means that you cannot create a textarea input and use autocomplete on it.
After looking at these documents:
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
It appears that 'type' is NOT an option to be passed into autocomplete (it is used in the form function apparently).
So, here is my hack to workaround this in the autocomplete function:
$index = array_search('type',$this->ajaxOptions);
$this->ajaxOptions[$index] = null;
$htmlOptions = $this->__getHtmlOptions($options);
$this->ajaxOptions[$index] = 'type';
2011-04-22 01:41:09
Hi!
Really cool.
Any plans to port this to cakephp 1.3 using the Js helper?
Regards.
2011-04-24 02:34:18
Hi!
This helper is very helping! Thanks!
I am maybe missing something but I don't get how to fill a hidden input with id while filling the autocomplete field with the value.
The following code is working but not very clean...
<input type="hidden" id="hiddenDiv"></input>
<?php echo $ajax->autocomplete('lb_projet', '/projets/ac_lb_projet', 'formatResult' => 'return data[0];')); ?>
<script type="text/javascript">
$("#LbProjet").autocomplete().result(function(evt,data,formatted){$("#hiddenDiv").val(data[1]);});
</script>
Thanks for your help.
Regards.
2011-04-29 06:00:49
Hi Thomas,
I think that your solution is best for this helper.
Thanks for sharing
2011-05-10 23:20:25
Hi kvas,
I've got a problem using autoComplete.
Nothing append when I try to write something in the input.
My Controller:
function autocomplete() {
$this->layout = 'ajax';
$this->set('especes', $this->Espece->find('all', array('conditions' => array(
'Espece.title LIKE' => '%'.$this->params['url']['q'].'%'),
'fields' => array('title'))));
$this->autoRender = true;
}
My form view
echo $form->create('Espece', array('url' => array('action' => 'edit')));
echo $ajax->autoComplete('espece_free', '/especes/autocomplete');
My autocomplete.ctp
<?php
foreach($especes as $espece){
echo $espece['Espece']['title'];
}
?>
I don't understand because i've got nothing in Firebug, even in Network tab...
However, i got
<script type="text/javascript">
//<![CDATA[
$('#EspeceFree').autocomplete('/crapalbonsai/especes/autocomplete', {});
//]]>
</script>
generated in the HTML source.
I don't understand why. I've got your latest version.
2011-05-10 23:43:52
Note : In the same page i also use a DatePicker and the DatePicker is working.
2011-05-11 08:22:01
Hi Crapal,
Maybe you can paste more HTML generated by helper?
Without it I can't say what is wrong...
2011-05-11 09:10:07
kvas, thanks for you answer.
Here is the full HTML generated by Helper
<div class="input text"><label for="EspeceFree">Espece Free</label><input name="data[Espece][espece_free]" type="text" id="EspeceFree" autocomplete="off" maxlength="200" /></div>
<script type="text/javascript">
//<![CDATA[
$('#EspeceFree').autocomplete('/crapalbonsai/especes/autocomplete', {});
//]]>
</script>
I've tried something else.
The autoComplete works when I don't include the jquery.ui.js script... I think that the problem is the jquery.ui.js script... but i need it for the datePicker.
Here is the datePicker generated script
<div class="input text required"><label for="BonsaiDateObtention">Date d'obtention</label><input name="data[Bonsai][date_obtention]" type="text" id="BonsaiDateObtention" /></div><script type="text/javascript">
//<![CDATA[
var BonsaiDateObtention = $('#BonsaiDateObtention').datepicker({maxDate:'+1Y', firstDay:1, dateFormat:'yy-mm-dd', dayNamesMin:["dim","lun","mar","mer","jeu","ven","sam"], monthNames:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Décembre"], showAnim:'blind', showOn:'both', buttonImage:'/crapalbonsai/img/date-icon.png', autoSize:true});
//]]>
</script>
2011-05-11 09:29:34
I fixed it by putting the include of jquery.ui BEFORE the jquery.autocomplete...
Thanks again ;)
2011-05-23 07:43:36
Hello, kvas.
First, I wanna say thanks for the helper. Its very helpful.
But, I need to ask you one thing. It's about how could I use my own <ul> on the view? Is it possible or not?
What I wanna do is, I'd like to set the attribut of the li with my own datas, on multiple autocomplete purpose.
Thank you in advance
2011-05-23 11:37:47
Hi guys,...
What am I doing wrong...??? can not get it work... nothing shows in a field...
in a blogs_controller.php
function autoComplete()
{
$this->set('blogs', $this->Blog->find('all', array('conditions' => array('Blog.name LIKE' => '%'.$this->data['Blog']['name'].'%'), 'limit' => 3, 'fields' => array('name'))));
$this->set('blogs',$blogs);
$this->layout = 'ajax';
}
in a views ...
../elements/header
<?php echo $javascript->link('prototype') ?>
<?php echo $javascript->link('lightbox') ?>
<?php echo $javascript->link('scriptaculous') ?>
<?php echo $javascript->link('effects') ?>
<?php echo $javascript->link('tooltip') ?>
<?php echo $javascript->link('jquery-1.4.2.min') ?>
<?php echo $javascript->link('jquery.autocomplete.min') ?>
<?php echo $javascript->link('jquery.jeditable.mini') ?>
also
../blogs/auto_complete.ctp
<ul>
<?php foreach($blogs as $blog): ?>
<li><?php echo $blog['Blog']['name']; ?></li>
<?php endforeach; ?>
</ul>
<div class="auto_complete"></div>
and in a search view . ctp
<?php echo $form->create('Blog', array('url' => '/blogs/search')); ?>
<?php echo $ajax->autoComplete('Blog/name', '/blogs/autoComplete')?>
<?php echo $form->end('Search')?>
THANK YOU for the helper ...
please help me to make it work...
2011-05-23 11:41:51
I also have this in a header...
<?php echo $html->css('application') ?>
<?php echo $html->css('photonotes') ?>
<?php echo $html->css('lightbox') ?>
<?php echo $html->css('jquery-ui-1.8.4.custom') ?>
<?php echo $javascript->link('application') ?>
<?php echo $javascript->link('swfobject') ?>
<?php echo $javascript->link('photonotes') ?>
<?php echo $javascript->link('ddlevelsmenu') ?>
<?php echo $javascript->link('highslide') ?>
<?php echo $javascript->link('highslide-html') ?>
<?php echo $html->css('haccordion') ?>
<?php echo $javascript->link('haccordion') ?>
above all...
maybe this is keeping from work...
2011-05-23 23:01:44
@thom - I think that it should be easier to write your code with jquery (without my helper).
@chris - did you get any error? Or maybe you can say what is wrong?
Maybe name of your field? Try 'Blog.name' instead of 'Blog/name'.
2011-05-28 11:20:24
?php echo $form->create('User', array('url' => '/ajax/view')); ?>
<?php echo $ajax->autoComplete('Post.subject', '/ajax/autoComplete')?>
<?php echo $form->end('View Post')?>
while using these, i am getting the error message like. call the member function and undefined varible ajax....
plz help me.. wat to do .....
i waiting for the reply...
2011-05-28 12:27:35
use the helpers... the problem ll slove
2011-08-08 23:18:59
I can get my autocomplete to successfully search through my cities and display the correct city, but when I click my selection, nothing happens and the text box text won't change. What do I need to do in order for the selection to be made after clicking the desired result?
echo $this->Ajax->autoComplete('City.name', '/cities/autoComplete');
2011-08-09 07:47:09
Hi John,
I've never problem like yours. Can you see in your errors console and paste here what is wrong?
2011-08-09 16:23:29
I got it to correctly insert the text for the city, but I can't seem to pass the id associated with the city... How can you pass the id?
2011-08-09 16:28:02
Hi John,
This helper does not provide such feature...
You must write your own piece of JavaScript code, but you can use js library that is used by my helper.
2011-08-19 05:09:18
hi kvas '
I got
$ is not a function
$('#ArticleTitle').autocomplete('/cakeplate/ajax/autoComplete', {});
thank
2011-08-19 07:45:50
Hi taq,
Did you included js libraries (like jQuery) in your layout.ctp ?
2011-08-29 09:07:38
Simplemente.. Gracias..
2011-09-27 09:00:05
Hello Kevas,
First of all,Thanks for neat and clean code.
I have put the style at the beginning of my ctp file.
but I do have problem with getting new div which includes all the results.
I have checked the response of Ajax request and it goes correctly and I'm getting all the data in firebug.
So I have problem with displaying data only.
Thanks in advance for your help..
here is the code..
jobposings_controller.php
function autoComplete()
{
if($this->RequestHandler->isAjax()) {
if(!empty($this->data['Jobposting']['title'])){
$jobpostings = $this->Jobposting->find('all', array('fields' => array('title'), 'conditions' => array( 'Jobposting.title LIKE' =>$this->data['Jobposting']['title'].'%'
),));
$this->set('jobpostings',$jobpostings);
$this->autoRender = true;
}
jobpostings/auto_complete.ctp
<?php foreach($jobpostings as $jobposting):?>
<?php echo $jobposting['Jobposting']['title'];?>
<?php endforeach; ?>
jobpostings/add.ctp
<?php echo $form->create('Jobposting',array('url'=>array('action'=>'add','controller'=>'jobpostings')));?>
<?php echo $ajax->autoComplete('Jobposting.title', '/jobpostings/autoComplete'); ?>
<?php echo $form->end();?>
2011-09-27 14:03:11
Hi Ashal,
Maybe problem is in css styles. Check in firebug if data goes into div with class="ac_results"...
2011-11-09 10:45:16
Hi Kevas,
Just a quick one: does your helper not require any jquery code, like using keyup event or something... if so what does it look like?
2011-11-09 20:15:35
Hi Molotsi,
My helper doesn't need javascrict code but it generates js (jquery) code and put it into your response.
2011-11-10 09:10:57
Thanks Kevas,
Am using CakePhp 1.3 and I just found out that (javascript and ajax) helpers are no longer supported there.
Am on 1.2 now and its working.
Please add in your step-by-step guide that people must download and link jquery.autocomplete.min.js
THANKS A LOT!!!
2011-11-10 12:46:20
Hi Molotsi,
File is placed in zip with my helper in section "download".
2011-11-10 18:39:53
I got everything working now, its all smooth thanks to the genius in you...you literally saved my life!
2011-12-15 23:11:20
First of all, great work!
But i remain with a struggle mention above.
<?php if(!empty($movies)){
foreach($movies as $movie){ ?>
<?php echo ($movie->title).'\n'; ?>
<?php }}else{
echo 'Not found'.'\n';
} ?>
This is in my autocomplete.ctp however the '\n' doesn't do a newline instead i get one big element including \n.
For example: Toy Story 3\n Toy Story 2\n.....
You know where my error is because I've been staring without luck. (also adding <br/> doesn't help since then it includes the <br/> into the result)
2011-12-17 19:52:46
My doesn't seem to work.
I have a user controller.
Do i have to declare autocomplete helper in my controller?
2012-01-31 09:39:04
Hi I'm using the new CakePHP 2.x
but when using autoComplete I cant be able to initiate any event.
My Code is
<?php echo $this->Ajax->autoComplete('User.username', '/message/search_user',array('autocomplete'=>'on', 'id' => 'username', 'empty' => 'Write the Username','type' => 'text', 'class' => 'input', 'div' => false, 'label' => false ));?>
but when typing inside it shows nothing.
I've included all the JS files and checked. Help me out please.
2012-01-31 13:12:07
Hi Dee,
Check in firebug if typing in field is triggering ajax request. If not check what js code was generated on your site, if Yes check what is response.
2012-02-12 23:38:59
Hi kvas!!
what a great helpers here and especially great support for those to ask (thx to kvas..)
i want to ask about sending options to autocomplete..
how to make function when i click one of the list??
i've tried :
$ajax->autoComplete('Transactiondetail0Product',
'/products/getProductListAjax',
array("label" => false,
"extraParams" =>
'select : function( event, ui ) {
$( "#TransactionProductId" ).val(ui.item.Product.id);
$( "#Transactiondetail0ProductId" ).val( ui.item.Product.name );
$( "#Transactiondetail0Amount" ).val( 1 );
$( "#Transactiondetail0Price" ).html( ui.item.Product.price );
return false;
})'));
2012-02-13 00:02:07
could it receive JSON formatted data??
2012-02-13 16:29:22
Hi Moo,
there is no callback on selecting item.
This autocomplete plugin cant receive JSON.
You can look at it's options here.
If you need to make not standard autocomplete I would suggest using http://jqueryui.com/demos/autocomplete/
2012-02-14 21:47:59
Hi kvas! ok then i'll use jqueryui then...thx for replying!
2012-02-15 17:27:23
Hi,
I have successfully implemented your autocomplete in cakephp 1.3. (THX kvas!) But I have a problem to send the id of the selected option to the controller. Only the text is sended, not the id.
I get successfully the answer of the controller: (output from firebug)
Option 344|3
Option 334|30
Option 234|31
I get the string 'Option ...' in the textbox (like I wanted), but I must send the ID to the controller.
I have tried:
echo $ajax->autoComplete('Option.name', '/giis/search2', array('formatResult' => 'return data[1];')); (cfr. Msg 20)==>Works: but the id is now in the textfield and the string must be in the textfield, the id must be in 'background'(=>hidden field???).
Can anybody help me?
Thx!
2012-02-16 18:46:07
Near to get it work.
when I put just a char, a strange list appears. If I continue to type letters, ok.
function autoComplete(){
$this->set('users', $this->User->find('all', array(
'conditions' => array(
'User.firstname LIKE' => '%'.$this->params['url']['q'].'%'
),
'limit' => $this->params['url']['limit'],
'fields' => array('firstname')
)));
}
The view is this
<?php
if (!empty($users)){
foreach($users as $u):?>
<?php echo $u['User']['firstname'];?>
<?php endforeach;
}
else
echo '';?>
I call the ajax like this
<?php echo $ajax->autoComplete('User.firtsname', '/users/autoComplete',array('div'=>false,'class'=>'field small-field'));?>
2012-02-17 07:22:55
Hi Don,
My helper doesn't support features like this. You should use jqeuryui autocomplete plugin and make it by your self.
@giuseppe - when you type chars in input it will retrive rows that contains these chars. If you want only rows that starts with your sequence you should delete first '%' in your query.
2012-03-20 16:33:15
First of all thanks for this great article, I have run the code and some of it is working but I get an empty named array when I use to print params array...
here is my code
echo $this->Ajax->autoComplete('Company.name', '/companies/autoComplete', array('class'=>'fullwidth'));
[output]
CakeRequest Object(
[params] = Array(
[controller] = companies
[action] = autoComplete
[named] =
Array(
)
[controller]
$this->set('results', $this->Company->find('all',
array('conditions'=> array('Company.name LIKE' => $this->params['url']['q']))));
Can you please help me to sort out this problem.. So that I can search the results
2012-03-21 07:43:27
hi Awais,
Did the problem appear on displaying form or response?
2012-03-21 22:51:52
Sorry I didn't mentioned that The problem appear when I enter some character in the textarea and it didn't show in params or request->data... that is it should be appear so that I can run the Controller->find (all, conditons = request->data ) statement...
I will also mention that I am using cakephp 2.0
2012-03-25 05:28:59
Hi Awais,
In cakephp2.x you should find params in: $this->request['url']
2012-03-26 00:46:12
well thanks for the help.. I also find some site where he update your code.. please check it
http://blog.rudylee.com/2011/07/25/jquery-ui-autocomplete-in-cakephp
thanks