mardi 4 janvier 2022

Simple Form non associated model checkbox

I'm running into a couple of problems, some of which, I think I have found a resolution. I'm trying to create a checkbox which will copy already filled in information to another form.

Let me try and paint the picture. I have a HomeAddress & OfficeAddress that belong_to a User. While many people are working from home these days, these addresses can both be the same, so when creating a User, I want them to be able to check a box which will copy the address information from HomeAddress to the OfficeAddress input fields.

<%= f.simple_fields_for :home_address do |f| %>
  <%= f.input :address %>
  <%= f.input :city %>
  <%= f.input :state %>
  <%= f.input :zipcode %>
<% end %>

<%= f.simple_fields_for :office_address do |f| %>
  <%= f.input :copy_home_address, as: :boolean, checked_value: true, unchecked_value: false, input_html: { checked: false id: 'copyPrimaryLocationAddress' } %>
  <%= f.input :address %>
  <%= f.input :city %>
  <%= f.input :state %>
  <%= f.input :zipcode %>
<% end %>

Couple of questions and problems I'm running into to start. Obviously adding the default value checked: false allows me to get around having to have this attribute exist on my OfficeAddress model. I am aware that I can create my own custom one which I'm fine with as well: app/inputs/fake_checkbox_input.rb(unsure how to get it to work):

class FakeCheckboxInput < SimpleForm::Inputs::StringInput
  # This method only create a basic input without reading any value from object
  def input(wrapper_options = nil)
    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
    tag_name = "#{@builder.object_name}[#{attribute_name}]"
    template.check_box_tag(tag_name, options['value'] || 1, options['checked'], options)
  end
end

This seems to get by the errors and association to a model that a form field has to have. However, the value ALWAYS stays the same. I'm trying to get it so that the value will change depending on when/if the checkbox is checked. Not to mention how to copy the information from the HomeAddress to the OfficeAddress which is a separate issue I dont know how to resolve.

Any tips on how to resolve or where to start would be helpful. I'm reading through the SimpleForm documentation but it just isn't making sense for my given circumstance.




Aucun commentaire:

Enregistrer un commentaire