sloanelybutsurely.com/lib/cms_web/live/post_live.ex
2025-02-22 13:59:24 -05:00

69 lines
2 KiB
Elixir

defmodule CMSWeb.PostLive do
@moduledoc false
use CMSWeb, :live_view
alias CMS.Posts
alias CMS.Posts.Post
@impl true
def handle_params(_params, _uri, %{assigns: %{live_action: :new}} = socket) do
post = %Post{}
changeset = Post.changeset(post)
socket = assign(socket, post: post, form: to_form(changeset))
{:noreply, socket}
end
def handle_params(%{"post_id" => post_id}, _uri, %{assigns: %{live_action: :edit}} = socket) do
post = Posts.get_post!(post_id)
changeset = Post.changeset(post)
socket = assign(socket, post: post, form: to_form(changeset))
{:noreply, socket}
end
@impl true
def handle_event("save_post", %{"post" => attrs}, %{assigns: %{live_action: :new}} = socket) do
socket =
case Posts.create_post(attrs) do
{:ok, post} -> push_navigate(socket, to: ~p"/admin/posts/#{post}")
{:error, changeset} -> assign(socket, form: to_form(changeset))
end
{:noreply, socket}
end
def handle_event("save_post", %{"post" => attrs}, %{assigns: %{post: post, live_action: :edit}} = socket) do
socket =
case Posts.update_post(post, attrs) do
{:ok, post} ->
assign(socket, post: post, form: post |> Post.changeset() |> to_form())
{:error, changeset} ->
assign(socket, form: to_form(changeset))
end
{:noreply, socket}
end
@impl true
def render(assigns) do
~H"""
<.form for={@form} class="flex flex-col gap-y-2" phx-submit="save_post">
<.input type="hidden" field={@form[:contents]} />
<.input class="border-gray-400 rounded" field={@form[:title]} />
<div id="editor" phx-update="ignore">
<trix-editor input={@form[:contents].id} class="prose prose-gray max-w-full"></trix-editor>
</div>
<button type="submit" class="self-end">save</button>
</.form>
<link rel="stylesheet" type="text/css" href="https://unpkg.com/trix@2.0.8/dist/trix.css" />
<script defer phx-track-static type="text/javascript" src={~p"/assets/editor.js"}>
</script>
"""
end
end