Skip to content

Instantly share code, notes, and snippets.

@baldrailers
Forked from tabishiqbal/_form.html.erb
Created November 24, 2021 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baldrailers/8425592c971a64cfcee78fae8295d410 to your computer and use it in GitHub Desktop.
Save baldrailers/8425592c971a64cfcee78fae8295d410 to your computer and use it in GitHub Desktop.
Tom-Select Example with Stimulus
import ApplicationController from "./application_controller"
import TomSelect from "tom-select"
export default class extends ApplicationController {
static values = { url: String }
connect() {
super.connect()
this.initTomSelect()
}
disconnect() {
if (this.select) {
this.select.destroy()
}
}
initTomSelect() {
if (this.element) {
let url = `${this.urlValue}.json`
this.select = new TomSelect(this.element, {
plugins: ['remove_button'],
valueField: 'id',
labelField: 'name',
searchField: ['name', 'email'],
maxItems: 1,
selectOnTab: true,
placeholder: "Select user",
closeAfterSelect: true,
hidePlaceholder: false,
preload: true,
create: false,
openOnFocus: true,
highlight: true,
sortField: {
field: "name",
direction: "asc"
},
searchField: 'name',
load: (search, callback) => {
fetch(url)
.then(response => response.json())
.then(json => {
callback(json);
}).catch(() => {
callback();
});
},
render: {
option: function (data, escape) {
return '<div>' +
'<span class="block">' + escape(data.name) + '</span>' +
'<span class="text-gray-400">' + escape(data.email) + '</span>' +
'</div>';
}
}
})
}
}
}
class UsersController < ApplicationController
def index
....
respond_to do |format|
...
format.json { render json: @users.map { |r| {name: r.name, id: r.id, email: r.email} } }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment