Skip to content

Instantly share code, notes, and snippets.

@schrockwell
Created September 16, 2019 12:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schrockwell/fdbdbd891bbad96e9644fc831ef0538d to your computer and use it in GitHub Desktop.
Save schrockwell/fdbdbd891bbad96e9644fc831ef0538d to your computer and use it in GitHub Desktop.
#
# This shows how to use an Ecto embedded schema as a form object as an interface between the
# HTML form and the LiveView's GenServer state.
#
defmodule RHRLiveWeb.Admin.UserListLiveView do
use Phoenix.LiveView
import Ecto.Changeset
defmodule SearchForm do
use Ecto.Schema
@primary_key false
embedded_schema do
field :search, :string
field :status, :string
field :service_id, :integer
end
end
def render(assigns) do
Phoenix.View.render(RHRLiveWeb.Admin.UserView, "list.html", assigns)
end
def mount(_session, socket) do
{:ok,
socket
|> assign(:changeset, change(%SearchForm{status: "!trash"}))
|> assign_users()}
end
def handle_event("search", %{"search_form" => params}, socket) do
{:noreply, do_search(socket, params)}
end
defp do_search(socket, params) do
changeset =
%SearchForm{}
|> cast(params, [:search, :status, :service_id])
socket
|> assign(:changeset, changeset)
|> assign_users()
end
defp assign_users(socket) do
list_opts =
socket.assigns.changeset
|> apply_changes()
|> Map.from_struct()
|> Map.to_list()
assign(socket, :users, RHRLive.Admin.Users.list_users(list_opts))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment