Demo : http://cbunny.rudylee.com/autocomplete_redirect
Demo source code : https://github.com/rudylee/cbunny
In my previous post ( http://blog.rudylee.com/2011/07/25/jquery-ui-autocomplete-in-cakephp/ ) we have successfully integrated the jQuery AutoComplete with CakePHP with a little bit hacky way. Now we gonna add another feature that can redirect user to our desired place when they click the result value in the AutoComplete ( try the demo for more details ).
So let’s start the coding ( I assume you have integrated the jQuery UI AutoComplete in your apps, if you haven’t, just read my previous post ), so basically what we need to do are divided into 4 steps:
- Wrap the jQuery UI AutoComplete search field in a form tag.
- Add a hidden field which will hold the ID of the result.
- Add ‘select’ option into the helper.
- Set up the action that will handle the form submit
Here is the sample code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php echo $this->Form->create('autoComplete',array('url' => array('controller' => 'users', 'action' => 'autoComplete'),'id' => 'GuestForm')); echo $this->Form->hidden('Guest.id'); echo $this->Ajax->autoComplete('Guest.search', array( 'source' => array( 'controller' => 'users', 'action' => 'autoComplete', 'prefix' => 'admin' ), 'select' => 'function(event, ui){ $("#GuestId").val(ui.item.id); $("#GuestForm").submit()}' )); ?> </form> |
As you can see in line 1, I defined the form and the controller + action that will handle the form submit. Line 2 is the hidden field that will hold the ID of the result. Line 3 is the AutoComplete form, I have added select option into the helper which will run the function defined to it each time user click the result. Line 10 means that the hidden field ( field that has ID GuestID ) will have value based on the AutoComplete Item ID ( which came from ui.item.id) and Line 11 will submit the form.
Here is the sample of the action code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function admin_autoComplete() { if (!empty($this->data)) { $this->redirect(array( 'controller' => 'users', 'action' => 'view', $this->data['Guest']['id'] )); } $this->autoRender = false; $guests = $this->User->getGuests(array( 'conditions' => array( 'OR' => array( 'User.name LIKE' => '%' . $_GET['term'] . '%', 'User.surname LIKE' => '%' . $_GET['term'] . '%' ) ) )); echo json_encode($this->User->autoComplete_encode($guests)); } |
Just ignore line 8 and so, we gonna focus on line 2 to 7. In that line, I redirect the user to the view action which based on the Guest ID which I got from the form. You can change the controller/action in this section. I hope everything is clear. Cheers.