afcapel / stimulus-autocomplete

Stimulus autocomplete component
MIT License
482 stars 62 forks source link

Pre-selected value #134

Closed danielfriis closed 1 year ago

danielfriis commented 1 year ago

First of all, thanks for the amazing work on this! Really nice work!

When I load a form containing an autocomplete field with a value already set, the 'search box' is empty.

It would be great to have the value of the search box reflect the value of the hidden field when that's already set on page load.

danielfriis commented 1 year ago

I found a solution which works well by adding the 'search term' as a virtual attribute on my model.

# app/models/my_model.rb

class MyModel < ApplicationRecord
  attr_accessor :search_term
end
# app/views/my_model/new.html.erb

# ...
<%= f.text_field :search_term, 'data-autocomplete-target': 'input' %>
# ...
# app/controllers/my_model_controller.rb

# ...
def program_params
    params.require(:program).permit(:title, :search_term)
end