AshNewar

AshNewar

Can show one help me to pass the values of the item to the modal when i click edit button

defmodule ZomatoWeb.Restraurents.RestraurentMenuLive do
  alias Zomato.Shops
  alias Zomato.Items
  alias Zomato.Item
  use ZomatoWeb, :live_view
  alias ZomatoWeb.NavbarComponent

  @impl true
  def mount(_params, %{"restraurent_token" => restraurent_token}=_session, socket) do
    restaurant = Shops.get_restraurent_by_session_token(restraurent_token)  # Assuming you have a way to get the restaurant ID from the session
    items = Zomato.Items.list_items_by_restaurant(restaurant.id)
    item = Items.change_item(%Item{})  # Create an empty changeset
    {:ok, assign(socket, items: items, restaurant_id: restaurant.id, item: item)}
  end

  @impl true
  def handle_event("save", %{"item" => item_params}, socket) do

    case Items.create_item(item_params, socket.assigns.restaurant_id) do
      {:ok, _item} ->
        {:noreply,
         socket
         |> Phoenix.LiveView.put_flash(:info, "Item created successfully.")
         |> Phoenix.LiveView.redirect(to: ~p"/restraurents/menu")}

      {:error, %Ecto.Changeset{} = changeset} ->
        {:noreply, assign(socket, changeset: changeset)}
    end
  end

  def handle_event("cancel", _, socket) do
    {:noreply, assign(socket, show_edit_modal: false, item: %{})}
  end


  @impl true
  def render(assigns) do
    ~H"""
    <div class="bg-gray-100">
      <div class="flex-col flex h-screen">
        <.live_component module={NavbarComponent} id={0}/>

        <div class="flex-1 p-6">
          <h2 class="text-3xl font-semibold mb-6">Menu Items</h2>

          <div class="mb-4">
            <button phx-click={show_modal("create_item")} class="bg-green-600 text-white font-bold py-2 px-4 rounded hover:bg-green-700">
              Add Item
            </button>
          </div>

          <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-6">
            <%= for item <- @items do %>
              <div class="bg-white rounded-lg shadow-md p-4">
                <div class="mb-4">
                  <img id="item-image" src="https://via.placeholder.com/150" alt="Menu Item Image" class="w-full h-32 object-cover rounded-md mb-2" />
                </div>
                <p class="text-gray-600 mb-4"><%= item.description %></p>
                <h3 class="text-xl font-semibold mb-2"><%= item.name %></h3>

                <div class="flex justify-between">
                  <button phx-click={show_modal("edit_item")} class="bg-blue-600 text-white py-1 px-3 rounded hover:bg-blue-700">Edit</button>
                  <button phx-click={show_modal("delete_item")} class="bg-red-600 text-white py-1 px-3 rounded hover:bg-red-700">Delete</button>
                </div>
              </div>
            <% end %>
          </div>
        </div>
      </div>
    </div>

    <.modal id="delete_item">
            <h2 class="text-2xl font-bold mb-4">Confirm Deletion</h2>
            <p class="mb-4">Are you sure you want to delete this item?</p>
            <div class="flex justify-between">
              <button phx-click="confirm_delete"  class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-700">
                Yes, Delete
              </button>
              <button phx-click="cancel"  class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-700">
                Cancel
              </button>
            </div>
    </.modal>

    <.modal id="create_item" >
        <h2 class="text-2xl font-semibold mb-4 text-center">Add Item Details</h2>
        <form phx-submit="save">
          <div class="mb-4">
            <label for="item_name" class="block text-sm font-medium text-gray-700">Item Name</label>
            <input type="text" name="item[name]" id="item_name" class="mt-1 block w-full border border-gray-300 rounded-md p-2" required />
          </div>

          <div class="mb-4">
            <label for="item_description" class="block text-sm font-medium text-gray-700">Description</label>
            <textarea name="item[description]" id="item_description" rows="3" class="mt-1 block w-full border border-gray-300 rounded-md p-2" required></textarea>
          </div>

          <div class="mb-4">
            <label for="item_price" class="block text-sm font-medium text-gray-700">Price</label>
            <input type="number" name="item[price]" id="item_price" step="0.01" class="mt-1 block w-full border border-gray-300 rounded-md p-2" required />
          </div>

          <div class="mb-4">
            <label for="item_category" class="block text-sm font-medium text-gray-700">Category</label>
            <input type="text" name="item[category]" id="item_category" step="0.01" class="mt-1 block w-full border border-gray-300 rounded-md p-2" required />
          </div>

          <div class="mb-4">
            <label for="item_image" class="block text-sm font-medium text-gray-700">Upload Image</label>
            <input type="file" name="item[image]" id="item_image" class="mt-1 block w-full border border-gray-300 rounded-md p-2" />
          </div>

          <button type="submit" class="mt-4 w-full bg-blue-600 text-white rounded-md py-2 hover:bg-blue-700">Add Item</button>
        </form>

    </.modal>

    <.modal id="edit_item">
        <h2 class="text-2xl font-bold mb-4">Edit Item</h2>
          <form phx-submit="save_changes" >
            <div class="mb-4">
              <label for="item_name" class="block text-sm font-medium text-gray-700">Item Name</label>
              <input type="text" id="item_name" name="item_name" value={"Ashish"} class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" required />
            </div>
            <div class="mb-4">
              <label for="item_description" class="block text-sm font-medium text-gray-700">Description</label>
              <textarea id="item_description" name="item_description" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" required>Descrip lik do</textarea>
            </div>  alias ZomatoWeb.CoreComponents

            <div class="mb-4">
              <label for="item_price" class="block text-sm font-medium text-gray-700">Price</label>
              <input type="number" id="item_price" name="item_price" value={55} class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-2" required />
            </div>
            <div class="flex justify-between">
              <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">Save Changes</button>
              <button phx-click="cancel" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-700">Cancel</button>
            </div>
          </form>

    </.modal>


    """
  end




end

please give me hint

First Post!

jimzhang.ex

jimzhang.ex

Try
mix phx.gen.live Sales Product products name:string price:integer description:string

Trace the code generated, and you’ll see how to show a modal and pass values to it.

Last Post!

_io2

_io2

So fundamentally, you aren’t passing values to your modal, you need to have some value already available in your assigns which your modal code can use.

@jimzhang.ex’s response - running a mix phx.gen.live and seeing what code Phoenix produces is your best bet to understand what is happening.

If after that, you did want to keep this single file approach, there are a few ways but one such approach could do be this …

  1. Assign an edit_item set to null in your mount() function.
  2. Add a handle_event("edit_item", %{"id" => item_id}, socket) which gets and updates the edit_item in socket.assigns based on the id of the item you clicked, send back your updated socket assigns
  3. Change your edit button’s click handler to do this {JS.push("edit_item", values: %{id: item.id}}
  4. Change your edit modal to include a show when edit_item isn’t null. @edit_item with the item you clicked on is now available in your modal for use.

Using another assign edit_item instead of item allows you to continue to be able to create_item without having to toggle @item when you cancel the edit modal.

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews