Skip to content

Instantly share code, notes, and snippets.

@tabishiqbal
Last active May 3, 2021 16:10
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 tabishiqbal/e8959c594d25c5306255e276daf9f240 to your computer and use it in GitHub Desktop.
Save tabishiqbal/e8959c594d25c5306255e276daf9f240 to your computer and use it in GitHub Desktop.
Stimulus Reflex populate dropdowns
class RegionReflex < ApplicationReflex
def select_state
state_id = element[:value].to_i
@state = State.find(state_id)
@state_cities = @state&.cities
end
end
<%= form_with model... %>
<div class="mt-6">
<%= form.label :state_id, class: "block text-sm font-medium text-gray-700" %>
<%# Here I add the data: {reflex: "change->Region#select_state"} - so for every new selection the reflex is triggered. %>
<%= form.collection_select(:state_id, State.all.order(name: :asc), :id, :name, { prompt: true }, data: {reflex: "change->Region#select_state"}, class: "drop-down") %>
</div>
<div>
<p>Select a city...</p>
<%# the variable @state_cities is then available from the reflex %>
<%= form.collection_select(:host_id, @state_cities.order(first_name: :asc), :id, :name, { prompt: true }, class: "drop-down") %>
</div>
<div>
<%= form.submit %>
</div
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment