Skip to content

Instantly share code, notes, and snippets.

View tslim's full-sized avatar

TS Lim tslim

View GitHub Profile
# In LiveView
<%= live_component @socket, MyApp.UserLive.CustomComponent, id: "custom", foo: "foo", bar: "bar" %>
# In custom_component.ex
socket.assigns.foo # returns "foo"
socket.assigns.bar # returns "bar"
# In CustomComponent Template
<%= @foo %>
<%= @bar %>
# in live_component.html.leex
<%= f = form_for @changeset, "#",
id: "form",
phx_target: @myself, # Don't forget this
phx_change: "validate",
phx_submit: "save" %>
# Link to send delete event to the live component
<%= link "Delete User", to: "#", phx_click: "delete", phx_target: @myself, phx_disable_with: "Deleting..." %>
# in router
scope "/", MyApp do
...
live "/users/new", UserLive.Index, :new
live "/users/:id/edit", UserLive.Index, :edit
...
end
# in live/user_live/index.html.leex
<%= if @live_action in [:new, :edit] do %>
scope "/" do
pipe_through [:browser, :admin_access]
live_dashboard "/admin/dashboard",
metrics: MyApp.Telemetry,
env_keys: ["RENDER_GIT_COMMIT"] # Depends on your infra setup
end
# Set root layout in pipeline
defmodule MyApp.Router do
pipeline :browser do
...
plug :put_root_layout, {MyApp.LayoutView, :root}
...
# Set root layout in routes
scope "/", MyApp do
defp apply_action(socket, :index, _params) do
assign(socket, :page_title, "Your Page Title")
end
# OR
def handle_params(params, uri, socket) do
{:noreply,
socket
|> assign(:page_title, "You Page Title")
...
def handle_params(params, uri, socket) do
{:noreply,
socket
|> assign(:uri, uri)
...
def handle_params(params, uri, socket) do
{:noreply,
socket
|> assign(:page, params["page"] || socket.assigns.page)
|> assign(:order_by, params["order_by"] || socket.assigns.order_by)
|> apply_action(socket.assigns.live_action, params)
|> fetch_users()}
end
def handle_event("search", %{"keyword" => keyword}, socket) do
def mount(_params, session, socket) do
{:ok,
socket
|> subscribe_to_pubsub()
...
end
def handle_info(_message, socket) do
{:noreply, fetch_users(socket)}
end
def mount(_params, _session, socket) do
{:ok, fetch_users(socket)}
end
def handle_event("delete", %{"id" => id}, socket) do
user = Accounts.get_user!(id)
{:ok, _} = Accounts.delete_user(user)
{:noreply, fetch_users(socket)}
end