Index with Links to Show Page

Listing Cats

NameColorOwnerCategory Actions
Marley Black Brian Real
MJ Tortoiseshell Brian Real
Mr. Business Gray Gayle Fictional
Garfield Orange Jon Fictional
Goose Orange Wendy Fictional

NOTE: reference the Setup section for generating the Animals context and adding the Cats to the database used in this example.

scope "/", LiveViewBasicsWeb do
  pipe_through :browser

  live "/cats", CatLive.Index, :index
  live "/cats/:id", CatLive.Show, :show
end
defmodule LiveViewBasicsWeb.CatLive.Index do
  use LiveViewBasicsWeb, :live_view

  alias LiveViewBasics.Animals

  def mount(_params, _session, socket) do
    socket = stream(socket, :cats, Animals.list_cats())
    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash}>
      <h1 class="text-4xl font-bold text-center">Index with Links to Show Page</h1>
      <.header>
        Listing Cats
      </.header>
      <div class="mb-2">
        <.table
          id="cats"
          rows={@streams.cats}
          row_click={fn {_id, cat} -> JS.navigate(~p"/cats/#{cat}") end}
        >
          <:col :let={{_id, cat}} label="Name">{cat.name}</:col>
          <:col :let={{_id, cat}} label="Color">{cat.color}</:col>
          <:col :let={{_id, cat}} label="Owner">{cat.owner}</:col>
          <:col :let={{_id, cat}} label="Category">{cat.category}</:col>
          <:action :let={{_id, cat}}>
            <div class="sr-only">
              <.link navigate={~p"/cats/#{cat}"}>Show</.link>
            </div>
          </:action>
        </.table>
      </div>
    </Layouts.app>
    """
  end
end
defmodule LiveViewBasicsWeb.CatLive.Show do
  use LiveViewBasicsWeb, :live_view

  alias LiveViewBasics.Animals

  def mount(%{"id" => id}, _session, socket) do
    socket = assign(socket, :cat, Animals.get_cat!(id))

    {:ok, socket}
  end

  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash}>
      <h1 class="text-4xl font-bold text-center">Index with Links to Show Page</h1>
      <.header>
        Cat {@cat.id}
      </.header>
      <div class="mb-2">
        <.list>
          <:item title="Name">{@cat.name}</:item>
          <:item title="Color">{@cat.color}</:item>
          <:item title="Owner">{@cat.owner}</:item>
          <:item title="Owner">{@cat.category}</:item>
        </.list>
      </div>
    </Layouts.app>
    """
  end
end
# The below functions already exist if you ran the context generator in the Setup
def list_cats do
  Repo.all(Cat)
end

def get_cat!(id), do: Repo.get!(Cat, id)