select2 not saving input for Edit
Asked Answered
D

2

10

For some reason when a user goes to edit an entry none of the data he had inputted via .select2 is shown. The data was saved though.

irb(main):001:0> Routine.find(1)
=> #<Routine id: 1, missed_days: 0, date_started: "2015-10-24 04:00:00", trigger: "brew tea", action: "stretch", user_id: 1, created_at: "2015-11-24 21:55:25", updated_at: "2015-12-14 21:00:09", committed: ["sun", "mon", "tue", "wed", "thu", "fri", "sat", ""], days_challenged: 30>

show.html.erb

enter image description here

edit.html.erb

enter image description here

_form.html.erb

<%= simple_form_for(@routine, remote: request.xhr?, html: { data: { modal: true } }) do |f| %> 
  <%= f.date_select :date_started, :order => [:month, :day, :year], class: 'date-select' %>
  <%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>
  <%= f.number_field :days_challenged, value: 30, class: 'day-challenge' %> <b>Day Challenge
  <label>After I</label> 
    <%= f.grouped_collection_select(:trigger, @trigger, :last, :first, :to_s, :to_s, include_blank: true) %><font color="#DDD">,</font>
  <label>I will</label> 
    <%= f.grouped_collection_select(:action, @action, :last, :first, :to_s, :to_s, include_blank: true) %>.
  <%= button_tag(type: 'submit', class: "btn")  do %>
   Save
  <% end %>
<% end %>

<script>
  $("#routine_trigger").select2({
    placeholder: "Existing Habit (Optional)",
    theme: "classic",
    allowClear: false,
    tags: true,
    multiple: false,
  });
  $("#routine_action").select2({
    placeholder: "Enter Challenge",
    allowClear: false,
    tags: true,
    multiple: false,
  });
</script>

routines_controller

  def new
    @trigger = 
    [
    ['Morning', ['Get Out of Bed', 'Clean Up Breakfast', 'Brush My Teeth', 'Sit at Desk', 'Start My Computer']], 
    ['Afternoon', ['Drink Coffee', 'Read Email', 'Eat Lunch', 'Use the Bathroom', 'Go for a Walk']],
    ['Evening', ['Enter My Home', 'Eat a Snack', 'Make a Drink', 'Shower', 'Finish Dinner']]
    ]
    @action = 
    [
    ['Mind', ['Write 500 Words', 'Read a Chapter', 'Study 20 min', 'Watch a Ted Talk', 'Take a Picture']], 
    ['Body', ['Do 25 Pushups', 'Juice Cleanse', 'Walk 10,000 Steps', 'Exercise', 'Eat an Apple']],
    ['Spirit', ['Meditate', 'Write 3 Gratitudes', 'Journal', 'Not Complain', 'Do a Random Act of Kindness']]
    ]
    if current_user == nil
      @routine = Routine.new
    else
      @routine = current_user.routines.build
      respond_modal_with @routine
    end
  end

  def edit
    @trigger = 
    [
    ['Morning', ['Get Out of Bed', 'Clean Up Breakfast', 'Brush My Teeth', 'Sit at Desk', 'Start My Computer']], 
    ['Afternoon', ['Drink Coffee', 'Read Email', 'Eat Lunch', 'Use the Bathroom', 'Go for a Walk']],
    ['Evening', ['Enter My Home', 'Eat a Snack', 'Make a Drink', 'Shower', 'Finish Dinner']]
    ]
    @action = 
    [
    ['Mind', ['Write 500 Words', 'Read a Chapter', 'Study 20 min', 'Watch a Ted Talk', 'Take a Picture']], 
    ['Body', ['Do 25 Pushups', 'Juice Cleanse', 'Walk 10,000 Steps', 'Exercise', 'Eat an Apple']],
    ['Spirit', ['Meditate', 'Write 3 Gratitudes', 'Journal', 'Not Complain', 'Do a Random Act of Kindness']]
    ]
    respond_modal_with @routine
  end
Discrown answered 15/12, 2015 at 20:8 Comment(6)
did you try selected: f.object.something?Circumlunar
Are you resetting the select2 value after successfully submitting?Levesque
If I hit save on the edit form then it will reset whatever the value was unless I put the value back in @LevesqueDiscrown
I mean in html's selected optionCircumlunar
Can you provide a fiddle so we can see?Levesque
Sorry @Levesque i dont know howDiscrown
Y
3

This is what I do on my select2 fields

<%= f.input :field_name, as: :select, collection: f.object.field_name, include_blank: false, selected: f.object.field_name, input_html: { class: "json_data" }, %>

json_data is how I make the text field into a select 2

coffee

$('.json_datas').before ()->
    "<input name='#{@.name}' type='hidden' />"
  $('.json_data').select2
    allowClear: true,
    placeholder: "Select a value",
    ajax:
      url: '/api/call_to_data'
      dataType: 'json'
      delay: 250
      data: (params) ->
        {
          q: params.term
          page: params.page
        }
      processResults: (data, page) ->
        # parse the results into the format expected by Select2.
        # since we are using custom formatting functions we do not need to
        # alter the remote JSON data
        { results: data.items }
      cache: true

I hope that this helps you

Ynez answered 18/12, 2015 at 22:38 Comment(2)
I'm struggling with your code here. Is there no way to do it with grouped_collection_select?Discrown
what I do is I have a regular text field that then select2 makes it into a select field. What is important to know is that I use a class called json_data that jquery performs action on. When Using select2 I like to include a hidden field with the same name of the as the field I want to use select2 on just in case of nil values. but its important to know that the data to populate the vales comes from the ajax urlYnez
G
0

Since you are using the method grouped_collection_select for the select field, it would make more sense to pass the :selected value(s) in the options hash for select. Obviously, you can pass it as blank when you are calling the partial from new.html.erb and you can pass some value to select when you are calling the partial from edit.html.erb for editing.
E.g.
grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name, { :selected => [1, 5, 6 ] } )

Read more at: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/grouped_collection_select#1538-Preselecting-options

Greatgranduncle answered 22/12, 2015 at 11:2 Comment(2)
Sure, then set the :selected to the values you want when you render the form for editing, otherwise leave the :selected array blank.Greatgranduncle
Since you are using a form partial, you can pass a variable with the values for :selected option. While calling the form partial from new.html.erb, send this variable as [] and while calling the form partial from edit.html.erb pass this variable as [some_value] for :selected option. Therefore, the value in select box will only appear while editing the form. Hope, it helps!Greatgranduncle

© 2022 - 2024 — McMap. All rights reserved.