Rails tom-select如何在编辑表单中保持已选值?

huangapple go评论68阅读模式
英文:

Rails tom-select how to keep selected value in edit form?

问题

这是您要翻译的内容:

"我有一个使用Ajax搜索正常工作的Tom-Select字段。当我选择要编辑的记录时,表单不显示所选位置的任何值。我试图设置默认字段,但没有任何值显示出来。它始终为空,显示默认的占位文本。有谁知道如何在编辑字段时保留保存的值吗?

选择字段:

<%= 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控制器:

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方法在控制器中

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

控制器:

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

希望这些翻译对您有帮助。如果有任何问题,请随时提问。

英文:

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:

&lt;%= form.select field.name,   [], {}, placeholder: &#39;Type to search&#39;, data: {controller: &#39;ts--search&#39;, ts__search_url_value: autocomplete_srs_path, ts__search_selected_value: @selected_for_tomselect.to_json }, :required =&gt; field.required %&gt;

Stimulus controller:

        import { Controller } from &quot;@hotwired/stimulus&quot;
import { get }        from &#39;@rails/request.js&#39;
import TomSelect      from &quot;tom-select&quot;
export default class extends Controller {
static values = { url: String, selected: String }
connect() {
this.element.setAttribute( &quot;autocomplete&quot;, &quot;off&quot; );
if (this.selectedValue == &#39;null&#39;) {
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 &lt; selected_json_data.length; i++) {
selected_items_array.push(selected_json_data[i].id)
}
}
var config = {
plugins: [&#39;clear_button&#39;, &#39;remove_button&#39;],
shouldLoad:function(q){
return q.length &gt; 2;
},
render: {
option: this.render_option,
item: this.render_option
},
loadThrottle: 300,
valueField: &#39;id&#39;,
options: selected_json_data,
items: selected_items_array,
sortField: {
field: &quot;description&quot;,
direction: &quot;asc&quot;
},
load: (q, callback) =&gt; 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: &#39;json&#39;
})
if(response.ok) {
callback(await response.json)
} else {
callback()
}
}
render_option(data, escape) {
if(data.description)
return `
&lt;div&gt;
${escape(data.description)}&lt;/div&gt;
&lt;/div&gt;`
else
return `&lt;div&gt;${escape(data.text)}&lt;/div&gt;`
}
}

Edit method in controller:

@selected = get_location(@sr.properties.as_json[&#39;location&#39;]).description
@selected_for_tomselect = @selected

controller:

  def autocomplete
list = Location.order(:description).where(&quot;description like :q&quot;, q: &quot;%#{params[:q]}%&quot;)
render(json: list.map do |u| { text: u.description, value: u.id } end)
end

答案1

得分: 1

你需要在编辑记录时填写选项参数和项目参数的数据。

看一下我是如何解决相同问题的:
https://github.com/nkokkos/rails_7_modal_form/

英文:

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/

huangapple
  • 本文由 发表于 2023年2月7日 05:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定