feat(chat): add events to validate/save chat in live view

This commit is contained in:
João Paulo Dubas 2024-10-18 11:07:26 +00:00
parent a0d23e5672
commit 2064ea8fb6
Signed by: joao.dubas
SSH Key Fingerprint: SHA256:V1mixgOGRc/YMhGx/DNkOSmJxgA2vHNrDZEk3wt/kOA

View File

@ -19,7 +19,7 @@ defmodule SlaxWeb.ChatRoomLive.Edit do
</.link>
</:actions>
</.header>
<.simple_form for={@form} id="room-form">
<.simple_form for={@form} id="room-form" phx-change="validate-room" phx-submit="save-room">
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:topic]} type="text" label="Topic" />
<:actions>
@ -43,6 +43,32 @@ defmodule SlaxWeb.ChatRoomLive.Edit do
{:ok, socket}
end
@impl Phoenix.LiveView
def handle_event("save-room", %{"room" => room_params}, socket) do
socket =
case Chat.update_room(socket.assigns.room, room_params) do
{:ok, room} ->
socket
|> put_flash(:info, "Room #{room.name} updated succesfully")
|> push_navigate(to: ~p"/rooms/#{room}")
{:error, changeset} ->
assign_form(socket, changeset)
end
{:noreply, socket}
end
@impl Phoenix.LiveView
def handle_event("validate-room", %{"room" => room_params}, socket) do
changeset =
socket.assigns.room
|> Chat.change_room(room_params)
|> Map.put(:action, :validate)
{:noreply, assign_form(socket, changeset)}
end
defp assign_form(socket, %Ecto.Changeset{} = changeset) do
assign(socket, :form, to_form(changeset))
end