![]() |
|
Snippets |
|
The Ajax helper function input_auto_complete_tag() is great stuff. You might have seen something comparable in Google Suggest. However, you might encounter some limitations when using it. Just imagine, you want to use it as a search field. Once you found the desired keyword, you might want to retrieve the whole record related to it. Unfortunately, after selecting an entry, the input field contains a search string, and mostly this is not unique in your database. As a consequence, you want to use the id of the record to perform the database select.
First of all we need to have a technique to unambiguously identify all options of the AutoComplete field:
<ul> <?php foreach ($object as $key => $value): ?> <li id="<?php echo $key ?>"><?php echo $value ?></li> <?php endforeach; ?> </ul>
It's simple: We just add an id attribute to the list element. Note that this example uses an associative array containing the unique id as key and the name (appearing as option) as value.
The trouble is now: how to access the id attributes of the list elements?
The input_auto_complete_tag() function can take an option called 'after_update_element' as a hook for a user-defined function. This receives 2 parameters:
(1) the autocompletion input field
(2) the selected item
For more Details take a glance at the documentation: http://wiki.script.aculo.us/scriptaculous/show/Ajax.Autocompleter
By including this option in our input_auto_complete_tag() function, we have the right tool for accessing the list element and doing nice things:
<?php echo form_remote_tag(array( 'url' => 'yourModule/calledAction', 'update' => 'resultarea', 'loading' => "Element.show('indicator')", 'complete' => "Element.hide('indicator')", )) ?> <?php echo input_hidden_tag('unique_id', '') ?> <?php echo input_auto_complete_tag('phrase', '', 'yourModule/autoCompleteAction', array('autocomplete' => 'off', 'size' => '30'), array('use_style' => 'true', 'after_update_element' => "function (inputField, selectedItem) { $('unique_id').value = selectedItem.id; }")); echo submit_tag('Go') ?> </form>
In the function definded for 'after_update_element' we set the unique_id attribute of the previously definded hidden field by accessing the 2nd parameter. This hidden field will then provide the unique_id within the target action.
Comments on this snippet
2 words: BRA VO !!!
Excellent piece of code !!! It saved me a LOT of pain ! :)
Thanks A LOT !