Last active
May 3, 2021 16:10
-
-
Save tabishiqbal/e8959c594d25c5306255e276daf9f240 to your computer and use it in GitHub Desktop.
Stimulus Reflex populate dropdowns
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 RegionReflex < ApplicationReflex | |
def select_state | |
state_id = element[:value].to_i | |
@state = State.find(state_id) | |
@state_cities = @state&.cities | |
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
<%= 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