Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Multiple input for collection. #867

Closed
mishatatinets opened this Issue Jul 11, 2012 · 4 comments

Comments

Projects
None yet
4 participants

I have a issue with select input.
If use single insert it works fine, but when I pass multiple => true

  f.input :category_id,
              :as => select,
              :multiple => true,
              :input_html => { :class => "chosen-input",  :style => "width: 700px;"},
              :collection => Category.all

I have a weird in put into database that stars with empty insert. Looks like it sending data to_yaml or simply separates them by "\n-"(my guess, it split by new lines )

Here what I get in console

["category_id", "---\n- ''\n- '180'\n- '288'\n- '392'\n"]

I wonder why it passing an empty string, and how I can get rid of it.

I guess I need changing existing input behavior, but not sure which one. My purpose is to record string of comma separated ids.

Owner

justinfrench commented Jul 11, 2012

Hi, if you inspect the params hash in your controller after submitting the form, you'll see that category_id is an array of ids. If you want to transform this into a string of comma separated numbers, you'll need to do that work yourself server-side (either in the controller, or preferably, the model).

I'd like to warn you though that you're going against the Rails and ActiveRecord conventions that Formtastic relies upon, so you'll find that the right categories won't be pre-selected when editing this object through a form. You should be creating a has_many :through or has_and_belongs_to_many association called :categories, at which time your Formtastic code would look like this:

f.input :categories,
              :as => select,
              :multiple => true,
              :input_html => { :class => "chosen-input",  :style => "width: 700px;"},
              :collection => Category.all

How to change your models to include this association is out of scope for Formtastic, but if you do this, Formtastic will Just Work™ :)

Thank you so much for your help.

Setting default values:

:selected => 'black'

or

:selected => ['black','blue']

juggleross commented Mar 3, 2017 edited

It's working for me:

permit category_ids params:

    permit_params category_ids: []

and add:

   input :category_ids, collection: Category.all.collect {|x| [x.name, x.id]}, as: :select, multiple: true, input_html: { class: "chosen-input",  style: "width: 700px;"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment