Skip to content

Commit 300d784

Browse files
committed
Fetch options for one dropdown based off the selected value of another dropdown
1 parent 29ef5f1 commit 300d784

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
defmodule LiveCalWeb.OrganizationUserSearchLive do
2+
use LiveCalWeb, :live_view
3+
4+
def mount(_params, _session, socket) do
5+
organization_options = for org <- get_organizations(), do: {org.name, org.id}
6+
7+
{:ok,
8+
socket
9+
|> assign(:form, to_form(%{"organization_id" => nil, "user_id" => nil}))
10+
|> assign(:organization_options, organization_options)
11+
|> assign(:user_options, [])}
12+
end
13+
14+
def handle_event("select-organization", %{"organization_id" => org_id} = form_params, socket) do
15+
user_options = for user <- get_organization_users(org_id), do: {user.name, user.id}
16+
17+
{:noreply,
18+
socket
19+
|> assign(:form, to_form(form_params))
20+
|> assign(:user_options, user_options)}
21+
end
22+
23+
def handle_event("submit", %{"organization_id" => organization_id, "user_id" => user_id}, socket) do
24+
IO.puts("~~ form submitted for organzation id: #{organization_id} and user id: #{user_id}~~")
25+
{:noreply, socket}
26+
end
27+
28+
def render(assigns) do
29+
~H"""
30+
<.form for={@form} phx-submit="submit">
31+
<.input field={@form[:organization_id]} phx-change="select-organization"
32+
type="select"
33+
label="First select an organization to load its users:"
34+
placeholder="organization"
35+
options={@organization_options}
36+
prompt="-- select organization --"
37+
/>
38+
<.input field={@form[:user_id]}
39+
type="select"
40+
label="Now select an organization user:"
41+
placeholder="user"
42+
options={@user_options}
43+
prompt="-- select user --"
44+
/>
45+
<button>Submit</button>
46+
</.form>
47+
"""
48+
end
49+
50+
# stubbed users and organizations
51+
defp get_organizations(), do: [%{id: 1, name: "OrgA"}, %{id: 2, name: "OrgB"}]
52+
defp get_organization_users(organization_id) do
53+
case organization_id do
54+
"1" -> [%{id: 1, name: "John from OrgA"}, %{id: 2, name: "Jules from OrgA"}]
55+
"2" -> [%{id: 3, name: "Jack from OrgB"}, %{id: 4, name: "Jill from OrgB"}]
56+
end
57+
end
58+
end

lib/live_cal_web/router.ex

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ defmodule LiveCalWeb.Router do
2929
live "/events", EventLive.Index, :index
3030
live "/events/new", EventLive.Index, :new
3131
live "/events/:id/edit", EventLive.Index, :edit
32+
33+
live "/organization_user_search", OrganizationUserSearchLive
3234
end
3335

3436
# Other scopes may use custom stacks.

0 commit comments

Comments
 (0)