hendri-tobing

hendri-tobing

Populate a Select field based on previous Select field

I have database tables: Companies, Devices, and Signs. The device belongs_to a Company and the Company has_many Signs.

I want to show on the new device form:

  • a select box of the existing Companies, and
  • a select box of the Signs that is populated based on the company selection.

The select box of the signs is dynamically changed if the selected company changed.

How to achieve this?

So far this is my device_controller.ex

defmodule PortalWeb.DeviceController do
  use PortalWeb, :controller

  alias Portal.Fleet
  alias Portal.Fleet.Device


  def create(conn, %{"device" => device_params}) do
    with {:ok, %Device{} = device} <- Fleet.create_device_customer(device_params) do
      conn
      |> put_flash(:info, "The device is created successfuly")
      |> redirect(to: Routes.page_path(conn, :index))      
    end
  end

  def new(conn, _params) do
    changeset = Fleet.change_device(%Device{})
    customers = Fleet.list_customers()
    |> Enum.map(&{"#{&1.name}", &1.id})
    render(conn, "new.html", changeset: changeset, customers: customers)
  end
end

Thank you.

Most Liked

sfusato

sfusato

Basically you would have a phx-change event on the form which will fire on every input change. Then in the handle_event callback you will pattern match on your Company select value and see if it changed from the one you have in your socket assigns. If it did, fetch the new Signs and re-assign. This will re-render your liveview automatically.

While there isn’t an example exactly like your use-case in it, phoenix_live_view_example is a good way to peek at how things work.

Later edit: found this (the “Bike comparison” example)

hendri-tobing

hendri-tobing

Thank you for the suggestion and example. I managed to populate the select field by using LiveView.

As suggested, I use phx-change that will pattern match the Company select value, then fetch the new Sign based on the value. Also assign the selected value to the Company select field.

This is part of my LiveView file.

  def render(assigns), do: LiveDeviceView.render("form.html", assigns)

  def mount(session, socket) do
    companies = Portal.Fleet.list_companies()
    selected_company = nil
    
    {:ok,
     assign(socket,
       changeset: Fleet.change_device(%Device{}),
       companies: companies,
       selected_company: selected_company,
       signs: [],
     )}
  end

  def handle_event("populate_sign", %{"device" => params}, socket) do
    signs = Fleet.get_company(String.to_integer(params["company_id"]))
    companies = Portal.Fleet.list_companies()
    changeset = Fleet.change_device(%Device{})
    selected_company = String.to_integer(params["company_id"])

    {:noreply, assign(socket, signs: signs, companies: companies, selected_company: selected_company, changeset: changeset)}
  end

form.html.leex

<%= f = form_for @changeset, "#", [phx_change: :populate_sign, phx_submit: :save] %>

  <%= label f, :company_id %>
  <%= select f, :company_id, Enum.map(@companies, &{&1.name, &1.id}), prompt: "Select a company", selected: @selected_company %>
  <%= error_tag f, :companies %>

  <%= if @signs == [] do %>
    <%= if @selected_company != nil do %> 
      <p>This company has no Sign</p> 
      <%= link "Add a new sign for this company", to: Routes.company_path(@socket, :new) %>
    <% end %>
  <% else %>
    <%= label f, :sign_id %>
    <%= select f, :sign_id, Enum.map(@signs, &{&1.name, &1.id}), prompt: "Select a sign" %>
    <%= error_tag f, :signs %>
  <% end %>

    <%= submit "Save", phx_disable_with: "Saving..." %>
  </div>

</form>

Thank you again for all responses.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement