2

I have a tom-select field works fine with an ajax search. When I select the record to edit the form it does not display any value of what was selected as the location. I am trying to set the default field but nothing has allowed me to have any value show up. It is always blank with the default placeholder text. Does anyone know how to retain what value was saved when editing the field?

select field:

<%= form.select field.name,   [], {}, placeholder: 'Type to search', data: {controller: 'ts--search', ts__search_url_value: autocomplete_srs_path, ts__search_selected_value: @selected_for_tomselect.to_json }, :required => field.required %>

Stimulus controller:

        import { Controller } from "@hotwired/stimulus"
        import { get }        from '@rails/request.js'
        import TomSelect      from "tom-select"


        export default class extends Controller {
        static values = { url: String, selected: String }

        connect() {
            this.element.setAttribute( "autocomplete", "off" );
        
            if (this.selectedValue == 'null') {
            var selected_json_data   = new Array();
            var selected_items_array = new Array();
            } else {
                var selected_json_data = JSON.parse(this.selectedValue)
                var selected_items_array = new Array();
                for(let i = 0; i < selected_json_data.length; i++) {
                selected_items_array.push(selected_json_data[i].id)
                }
            }
            
            var config = {
            plugins: ['clear_button', 'remove_button'],
            shouldLoad:function(q){
                return q.length > 2;
            },
            render: {
                option: this.render_option,
                item: this.render_option

            },
            loadThrottle: 300,
            valueField: 'id',
            options: selected_json_data,
            items: selected_items_array,
            sortField: {
                field: "description",
                direction: "asc"
            },
        
            load: (q, callback) => this.search(q, callback),
            
            
            }
        
            let this_tom_select = new TomSelect(this.element, config)
            this_tom_select.clearCache()
            
        }


        async search(q, callback) {
            const response = await get(this.urlValue, {
            query: { q: q },
            responseKind: 'json'
            })

            if(response.ok) {
            callback(await response.json)
            } else {
                callback()
            }
        }


        render_option(data, escape) {

        if(data.description)
            return `
            <div>
                ${escape(data.description)}</div>
            </div>`
            else
            return `<div>${escape(data.text)}</div>`
        }

        }

Edit method in controller:

@selected = get_location(@sr.properties.as_json['location']).description
@selected_for_tomselect = @selected

controller:

  def autocomplete
    list = Location.order(:description).where("description like :q", q: "%#{params[:q]}%")
    render(json: list.map do |u| { text: u.description, value: u.id } end)
  end
spacerobot
  • 265
  • 1
  • 5
  • 23

1 Answers1

1

You need to fill in the data for the options parameter and items parameter as you edit the record.

Take a look at how I resolved the same problem: https://github.com/nkokkos/rails_7_modal_form/

Nick_K
  • 541
  • 6
  • 22
  • Thanks for including this! I am still having some issues getting this to work. I have a single value in the select so I do not need the array mapping for multiple items. I tried to strip that out. I have updated my original post. Can you advise what I am doing wrong? I know I am getting the correct values for @selected. The field just doesn't display anything when I click edit. – spacerobot May 09 '23 at 18:45
  • Can you get your solution to work on a regular select box? Tom-select builds upon the select html tag. For start, you need to pass an id to the select box to make it work. I don't understand what you are doing. You can not pass a text description for selected items. See how the select html tag works:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select – Nick_K May 11 '23 at 14:01
  • Thanks for getting back to me. I went through yesterday and changed that to pass the ID. I did manage to get it mostly working. It now displays the selected value when I edit a record. The only issue I am having is that if I delete the value and search again it returns no results. If I remove valueField: 'id' from the script it searches fine and displays the results but then when I edit a record it does not show the selected value. I updated my stimulus controller above. It is very similar to yours now. Any thoughts? – spacerobot May 11 '23 at 14:16
  • Your edit controller must return a single id and a json structure. See how I do it here:https://github.com/nkokkos/rails_7_modal_form/blob/main/app/controllers/items_controller.rb#L22. So, for your case, "@selected" should a number or an array of one number, for example, [13] where 13 could the id in your description table. "@selected_for_tomselect" should be a json structure containing an id and description. – Nick_K May 12 '23 at 07:00