btihen

btihen

Phoenix 1.7. & LiveView 0.20.2 - simple dropdown selector question

I am trying to build an admin panel - in one field I want a simple dropdown menu.
I found a way to do this, but I think I found a round-about way and hoping there is a straight forward way.

Here is what I did:

  1. add all the users to the assigns (so I could list them in the dropdown)
  2. hide the normal field that submits the user_id (but keep the value there) so that on save the value is submitted (probably possible to do from the select, but I couldn’t figure out how).
  3. add a select with all the users (and with the initial ‘selected’ value the same as the user_id in the form.
  4. wrote a handler to update the user_id in the changeset when the selected value changes.

Here is the code (for better or worse - but it works):

  def render(assigns) do
    ~H"""
    <div>
      <.header>
        <%= @title %>
        <:subtitle>Use this form to manage domains records in your database.</:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="domains-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:domain_name]} type="text" label="Domain name" />
        <.input field={@form[:domain_url]} type="text" label="Domain URL" />
        <.input field={@form[:domain_descriptioin]} type="text" label="Domain descriptioin" />
        <%!-- <.input field={@form[:user_id]} type="number" label="User ID" /> --%>
        <.input field={@form[:user_id]} type="hidden" />

        <label for="user_id">User</label>
        <select name="user_id" id="user_id" phx-change="select_user">
          <%= for user <- @users do %>
            <%= if user.id == @domains.user_id do %>
              <option value={user.id} selected><%= user.username %></option>
            <% else %>
              <option value={user.id}><%= user.username %></option>
            <% end %>
            <%!-- <option value={user.id}><%= user.username %></option> --%>
            <%!-- <% selected = if user.id == @form[:user_id], do: "selected", else: "" %> --%>
            <%!-- <option value={user.id} {selected}><%= user.username %></option> --%>
          <% end %>
        </select>
        <:actions>
          <.button phx-disable-with="Saving...">Save Domains</.button>
        </:actions>
      </.simple_form>
    </div>
    """
  end

  @impl true
  def update(%{domains: domains} = assigns, socket) do
    # add the full list of users for the dropdown selector
    users = ClearSync.Core.Accounts.list_users()
    socket = assign(socket, users: users)
    changeset = WorkDomains.change_domains(domains)

    {:ok,
     socket
     |> assign(assigns)
     |> assign_form(changeset)}
  end

  # update the user chosen in the changeset when the selector changes who is selected
  def handle_event("select_user", %{"user_id" => user_id}, socket) do]
    changeset =
      socket.assigns.domains
      |> WorkDomains.change_domains(%{"user_id" => String.to_integer(user_id)})

    # |> WorkDomains.change_domains(%{"user_id" => parsed_user_id})

    {:noreply, assign_form(socket, changeset)}
  end

This works, but

  1. it seems clumsy, I am assuming I have overlooked something fundamental
  2. my hidden .input field is hidden, but takes up visible white space

Note: I haven’t caught up on understanding the newest LiveView changes - I am sure my approach reflects that, in addition to helping me cleanup the whitespace and create a more elegant solution, If its clear what fundamental misunderstanding(s) I have - I would appreciate knowing where I can learn more - I will try to go through some liveview 1.7 tutorials, but if there is a short cut short of starting over, I would appreciate that.

Thanks,

Bill

Most Liked

bkilshaw

bkilshaw

@Mostalive covered it for the most part; using the build in core_components you can do something like this as long as you’re passing the users in.

  <.input
    field={f[:user_id]}
    type="select"
    label="User"
    options={Enum.map(@users, &{&1.username, &1.id})}
    prompt="Select a user"
  />

It might be better to just pass the list of tuples into the component instead of the list of full users depending on the situation.

You only need to pass in a “value” if you want to pre-select a specific value. Using the code above the component is smart enough to pre-select the correct user if you use the form component on an edit page.

btihen

btihen

Thanks for the example - works well. Definately, much simpler. :slight_smile:

btihen

btihen

Thanks for pointing me in the right direction and the documentaion.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
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
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
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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

We're in Beta

About us Mission Statement