Graeme
Graeme

Reputation: 481

Selected value based on a GET param using select_tag in Ruby on Rails

I have a working form (which is not bound to a model, and thus uses form_tag) which includes a select box.

The related code is as follows:

select_tag 'language', "<option value='ar' selected>Arabic</option>
<option value='bg'>Bulgarian</option><option value='ca'>Catalan</option>
<option value='zh-CHS'>Chinese (Simplified)</option>
<option value='zh-CHT'>Chinese (Traditional)</option>
...
<option value='tr'>Turkish</option><option value='uk'>Ukrainian</option>
<option value='vi'>Vietnamese</option>".html_safe

As you'll notice, Arabic is the default option, and there are approximately 35 languages in the list.

When the user chooses their language, I store the value separately (via the GET when the form is submitted), but I'd like the form to automatically select the user's chosen language the next time they encounter the form. In other words:

  1. The "default" option is Arabic;
  2. The user chooses French as their language;
  3. The next time they encounter the form (for example, when they return to the relevant page), French rather than Arabic is chosen.

One way I thought of achieving this was through a case...when call, in which the selected attribute is added to the relevant option, but with 35+ languages in the list, this is likely to get a bit fiddly, and I'm sure there's a better/tidier way.

Any ideas? I'm thinking options_for_select is the solution, but I'm not sure how this would go into the above code?

Upvotes: 1

Views: 1381

Answers (1)

Graeme
Graeme

Reputation: 481

Ha! Typically, I managed to resolve the issue within 10 minutes of posting this. You can use options_for_select, and the solution to my problem (for anyone with a similar query who happens to see this) is as follows:

select_tag 'language', 
options_for_select([
["Arabic", "ar"], 
["Bulgarian", "br"], 
["Catalan", "ca"],
....
], params[:get_language])

If params[:get_language] isn't set, i.e. there has been no previous form submission, then I don't think any of the options are selected (or, in other words, the first option in the list is the default selection) but I haven't tested this (I have more code elsewhere which checks whether this form is being called for the first time or not).

Sorry for wasting your time, folks!

Upvotes: 2

Related Questions