SlowBucket
SlowBucket

Reputation: 167

Can you change label display names when using simple-form in rails?

I am using simple-form in rails and I would like to know if there is a way to change the way collection objects are displayed. For example I have something like this

<%= f.input :lang, :label => "Language", :collection => [ "en", "es, "zh", "fr" ] %>

Instead of showing up as "en es zh" etc I would like it to show up as "English Spanish" etc to the user. Is there anyway to do that sort of thing?

Thanks in advance.

Upvotes: 13

Views: 16344

Answers (5)

ctappy
ctappy

Reputation: 177

 <%= f.input :lang, label: "Language", collection: [ [ "English", "en" ], [ "Spanish", "es" ], [ "French", "fr" ] ] %>

This works above, use a nested array. Also, this was used in the latest rails and simple form.

Upvotes: 0

wojtekk
wojtekk

Reputation: 626

My approach is to put entire collection in locale yml file (en.yml):

#RAILSROOT/locales/en.yml
en:
  collections:
    languages: 
      - - en
        - English
      - - de
        - Deutch

and in view just write:

<%= f.input :lang, :label => "Language", :collection => t("collections.languages") %>

I use this A LOT so I even wrote gem with helper functions which extends I18n (https://github.com/rstgroup/i18n-structure) and with that in gemfile you can write (notice "tc" helper)

<%= f.input :lang, :label => "Language", :collection => tc(:languages) %>

Upvotes: -1

user1193139
user1193139

Reputation:

You can use following way as well:

In Model:

    LANGUAGES = {'English' => 'en','French' => 'fr'}

In View:

    <%= f.input :lang, :label => "Language", :collection => Model::LANGUAGES %>

Upvotes: 19

Steve
Steve

Reputation: 2666

Another option is to add a helper

def languages_display
  [
    ["English", "en"],
    ["Spanish", "sn"],
    ["French", "fr"],
  ]
end

And then call your helper from the input field:

<%= f.input :state, :collection => languages_display %>

And then on your show view you could call the following helper so that it displays English and not the en you have in the db:

def show_language(language)
  {
    "en" => 'English',
    "sp" => 'Spanish',
    "fr" => 'French'
  }[language]
end

Upvotes: 0

pablomarti
pablomarti

Reputation: 2107

I guess that the label will be "English" and the value "en"; you can do something like this:

Store the data in a Model (recommended) or make a hash:

@data = Language.all

In the view use label_method and value_method:

<%= f.input :lang, :label => "Language", :collection => @data, :label_method => :name, :value_method => :value %>

Check the section Collections in https://github.com/plataformatec/simple_form

Upvotes: 0

Related Questions