Reputation: 297
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
Upvotes: 2
Views: 1054
Reputation: 633
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/
Upvotes: 1