Thursday, January 05, 2006

has-and-belongs-to-many with multiselect listboxes

If you have played with habtm in RoR, you might have encountered a need a provide a list that the user can select from. Usually, you would use a list of checkboxes to provide such a thing. Check out http://wiki.rubyonrails.com/rails/pages/CheckboxHABTM/versions/12 which shows a way to render such a thing.

But, It is a bit unweildy if you have long list that a user can select from, say, list of all cities in a state. In that case, I used a multi-select list box to provide such an implementation.

To generate the code, use the following method in your helpers. It basically takes 5 arguments, collection_name is a name for the collection that can be used in the controller, list_selections provides the collection of all possible selections, current_selections provides the current selection in the model, value_method is the method for the value, and text_method is the method for the text that can be called on the object contained within current_selections. Note that current_selections should have "include?" method implemented to determine the current selection.

def multi_select_collection(collection_name, list_selections, current_selections,value_method,text_method)
result = "<select name='#{collection_name}[]' multiple size=5>\n"
list_selections.each do |l|
result << "<option value='#{l.send(value_method)}'"
result << " selected " if current_selections.include?(l)
result << "/> #{l.send(text_method)} </option>\n"
end
result << "</select>\n"
return result
end

You might have to reformat it if you cut&paste since my blog might have wrapped it.


0 Comments:

Post a Comment

<< Home