-
-
Save wellsmuker/5d6d34d3aef464e45551067192b0677c 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 { Controller } from "stimulus" | |
| import TomSelect from "tom-select" | |
| export default class extends Controller { | |
| static values = { url: String } | |
| 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 |
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
| <div class="rounded-md shadow-sm"> | |
| <%= f.select :account_user_id, {}, {placeholder: "Select user"}, {class: "w-full", data: { controller: "select", select_url_value: users_path } }%> | |
| </div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment