nesimtunc

nesimtunc

How to get selected value of HTML options element on phx-click event

Hi,

Basically I’m coding an order system. There’re Products, Customer, Order and OrderItems tables.

My Order form is like attached capture.

Here’s my codes:
lib/myapp_web/live/admin/form_component.html.leex

<h2><%= @title %></h2>

<%= f = form_for @changeset, "#",
  id: "order-request-form",
  phx_target: @myself,
  phx_submit: "save" %>

  <%= label f, :customer_id %>
  <%= text_input f, :customer_id %>
  <%= error_tag f, :customer_id %>

  <%= label f, :order_id %>
  <%= text_input f, :order_id %>
  <%= error_tag f, :order_id %>

  <h2>Order Items</h2>
  <table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Count</th>
      <th></th>
    </tr>
  </thead>
  <tbody id="products">
  <tr>
    <td>
      <%= select f, :product_id, Enum.map(@products, &{&1.name, &1.id })%>
    </td>
    <td>
      <%= select f, :count, 1..50 %>
      <%= error_tag f, :count %>
    </td>
    <td>
      <button type="button" phx-click="add">+</button>
    </td>
  </tr>
  </tbody>
</table>

<h2>Cart</h2>
  <table id="cart" phx-update="append">
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
      <th>Count</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <%= for item <- @cart_items do %>
      <tr id="item-<%= item.id %>">
        <td><%= item.name %></td>
        <td><%= item.price %></td>
        <td></td>
        <td>
          <button type="button" phx-click="remove">-</button>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

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

</form>

lib/myapp_web/live/admin/index.ex

defmodule MyAppWeb.AdminLive.Index do
  use MyAppWeb, :live_view

  alias MyApp.{ Products, Orders }

  @impl true
  def mount(_params, _session, socket) do
    socket = socket |> assign(:pending_orders, load_pending_orders())
    {:ok, socket, temporary_assigns: [cart_items: []]}
  end

  @impl true
  def handle_params(params, _url, socket) do
    IO.inspect(params)
    IO.inspect(socket.assigns)
    {:noreply, apply_action(socket, socket.assigns.live_action, params)}
  end

  @impl true
   def handle_event("add", params, socket) do
      IO.puts("+++++++++++++++++ADDING+++++++++++++++++++")
      IO.inspect(params)
      IO.inspect(socket.assigns.cart_items)
      IO.puts("+++++++++++++++++ADDED+++++++++++++++++++")
      cart_items = socket.assigns.cart_items
      socket = assign(socket, :cart_items, cart_items)
		{:noreply, socket}
  end

  @impl true
  def handle_event("remove", params, socket) do
    IO.puts("+++++++++++++++++REMOVING+++++++++++++++++++")
    IO.inspect(params)
    IO.inspect(socket.assigns.cart_items)
    IO.puts("+++++++++++++++++REMOVED+++++++++++++++++++")
    cart_items = socket.assigns.cart_items
    socket = assign(socket, :cart_items, cart_items)
		{:noreply, socket}
   end

  defp apply_action(socket, :new, _params) do
    socket
    |> assign(:page_title, "New Order")
    |> assign(:order_request, nil)
    |> assign(:products, load_avaliable_products())
    |> assign(:cart_items, [%Products.Product{}])
  end

  defp apply_action(socket, :index, _params) do
    socket
    |> assign(:page_title, "Admin")
    |> assign(:pending_orders, load_pending_orders())
  end

  defp load_pending_orders do
     Orders.list_pending_orders()
  end

  defp load_avaliable_products do
	Products.list_avaliable_products()
  end

end

What I need is, getting selected values of ordered products when click the “+” button on server side.

How can I achieve this?

Thank you!

Marked As Solved

jayjun

jayjun

Add :phx_change to your <form> to get every input value update. Then assign selected input values into phx-value attributes.

<%= f = form_for @changeset, "#",
  id: "order-request-form",
  phx_target: @myself,
  phx_change: "change",
  phx_submit: "save" %>

<button type="button" phx-click="add"
  phx-value-product-id="<%= @add_product_id %>"
  phx-value-count="<%= @add_count %>">+</button>
def handle_event("change", params, socket) do
  # find product_id and count in params
  socket =
    socket
    |> assign(socket, :add_product_id, product_id)
    |> assign(socket, :add_count, count)

  {:noreply, socket}
end

def handle_event("add", %{"product_id" => product_id, "count" => count}, socket) do
  ...
end

Where Next?

Popular in Questions 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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
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
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
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

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 43657 311
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31194 112
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
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
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31307 143
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

We're in Beta

About us Mission Statement