Home > Mobile >  How to pass all values of radio button to controller in Formtastic form
How to pass all values of radio button to controller in Formtastic form

Time:02-03

So an issue that I'm facing is to getting all checkbox values to the controller when pushing submit button

index:

= semantic_form_for :account do |form|
  = render form, form: form
  = form.actions do
    = form.action :submit

form:

- current_user.organizations.each do |organization|
  - accounts = organization.accounts
    %label
      = organization.name
        - accounts.each do |account|
          = form.fields_for organization.id.to_s, account do |f|
            = f.hidden_field :id
            = f.radio_button :active, 1, checked: account.active
            = f.label account.name

Currently only checked data is passed: let's say that we do have 2 organizations with multiple accounts and you do check the radio button from both, in my case params that will be sent to the controller will be only the checked ones, like:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "account"=>{"organization.id"=>{"id"=>"account.id", "active"=>"1"}, "5"=>{"id"=>"account.id", "active"=>"1"}}, "commit"=>"Submit"}

But what I wish is to get into parameters all radio buttons, not only the clicked ones, so at the end, parameters will contain a full list and then i could operate with them in the controller

CodePudding user response:

You cannot. The browser will never send any unchecked button (being it radio or checkbox), only the checked ones.

What you can do is to use checkboxes. Rails will add a hidden field for you with the value "0", that you will only receive when the checkbox is unchecked.

See https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-check_box

  •  Tags:  
  • Related