|
| 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 |
0 commit comments