-
-
Save baldrailers/8425592c971a64cfcee78fae8295d410 to your computer and use it in GitHub Desktop.
Tom-Select Example with Stimulus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>'; | |
} | |
} | |
}) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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