sloanelybutsurely.com/lib/cms_web/live/post_live.ex

73 lines
2 KiB
Elixir

defmodule CMSWeb.PostLive do
@moduledoc false
use CMSWeb, :live_view
alias CMS.Posts
alias CMS.Posts.Post
@impl true
def mount(_params, _session, socket) do
socket = assign(socket, :load_trix?, true)
{:ok, socket}
end
@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="text-lg" field={@form[:title]} placeholder="Title" />
<div id="editor" phx-update="ignore">
<trix-editor input={@form[:contents].id} class="prose prose-cms max-w-none"></trix-editor>
</div>
<button type="submit" class="self-end">save</button>
</.form>
"""
end
end