November 21, 2006
Passing extra data with an auto_complete
I recently found myself trying to use an auto_complete field to allow the user to select an object from a list of possible objects. That’s all fine and dandy, but I wanted to exclude certain values depending on which object I was editing. There are at least two ways to do this, the first is to stuff the extra data into the session and then read that value from the auto_complete_for method and act appropriately.
I don’t really like this approach because I don’t want to clutter up the session with various form parameters. Thankfully, there is a simple way to do this by once again abusing the built in text_field_with_auto_complete function…
-
# View
-
<%= text_field_with_auto_complete ‘new_object’, ‘name’, { :tabindex=>1 }, {:url=>{:action=>’auto_complete_for_object_name’, :extra=>@object.extra} %>
[In my case, I used the :extra data to exclude certain objects from the auto_complete_for response]
By passing the :url option, you rewrite the URL that the AJAX actions call, enabling you to add extra parameters that can be acted on by the method. Also note that you can change the name of the action called (in fact, you need to specify it or it will default to the name of the action for the current view… probably not what you want). This is handy because it lets you assign the response to a variable with a different name without writing a separate auto_complete_for handler. In this case, the submitted form will have a ‘new_object[name]‘ in the params, even though the action called was ‘auto_complete_for_object_name’.
Needless to say, you need to write a custom ‘auto_complete_for’ method to handle the extra data. Note that you could also use this method to handle multiple auto_complete fields.
Filed by Kevin Olbrich at 3:23 pm under AJAX, Forms, Ruby on Rails, User Interface, auto_complete
2 Comments
Hey, thanks so much for this. It really helped me out. As another example, here’s my line of code:
‘off’, :style => ‘font-weight:bold;’, :value => ” }, { :url => { :action => :auto_complete_for_person_name, :person_id => @person.id } } %>
Then, in the Controller, I can access params[:person_id] to exclude that person’s name.
Thanks man, I just spent a whole day trying to do this and finally the url thing worked. Good deal.