2021-02-24 07:49:39 -05:00
|
|
|
defmodule Bones73kWeb.PropertyLive.FormComponent do
|
|
|
|
use Bones73kWeb, :live_component
|
2020-09-14 12:22:25 -04:00
|
|
|
|
2021-02-24 07:49:39 -05:00
|
|
|
alias Bones73k.Properties
|
2020-09-14 12:22:25 -04:00
|
|
|
|
|
|
|
@impl true
|
|
|
|
def update(%{property: property} = assigns, socket) do
|
2021-03-03 16:07:59 -05:00
|
|
|
socket
|
|
|
|
|> assign(assigns)
|
|
|
|
|> assign(:changeset, Properties.change_property(property))
|
|
|
|
|> live_okreply()
|
2020-09-14 12:22:25 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def handle_event("validate", %{"property" => property_params}, socket) do
|
|
|
|
changeset =
|
|
|
|
socket.assigns.property
|
|
|
|
|> Properties.change_property(property_params)
|
|
|
|
|> Map.put(:action, :validate)
|
|
|
|
|
|
|
|
{:noreply, assign(socket, :changeset, changeset)}
|
|
|
|
end
|
|
|
|
|
2021-03-05 15:32:01 -05:00
|
|
|
@impl true
|
2020-09-14 12:22:25 -04:00
|
|
|
def handle_event("save", %{"property" => property_params}, socket) do
|
|
|
|
save_property(socket, socket.assigns.action, property_params)
|
|
|
|
end
|
|
|
|
|
2021-03-05 15:32:01 -05:00
|
|
|
@impl true
|
|
|
|
def handle_event("cancel", _, socket) do
|
|
|
|
{:noreply, push_event(socket, "modal-please-hide", %{})}
|
|
|
|
end
|
|
|
|
|
2020-09-14 12:22:25 -04:00
|
|
|
defp save_property(socket, :edit, property_params) do
|
|
|
|
case Properties.update_property(socket.assigns.property, property_params) do
|
|
|
|
{:ok, _property} ->
|
2021-03-04 22:03:27 -05:00
|
|
|
flash = {:info, "Property updated successfully"}
|
|
|
|
send(self(), {:put_flash_message, flash})
|
|
|
|
|
2021-03-03 16:07:59 -05:00
|
|
|
socket
|
|
|
|
|> push_event("modal-please-hide", %{})
|
|
|
|
|> live_noreply()
|
2020-09-14 12:22:25 -04:00
|
|
|
|
|
|
|
{:error, %Ecto.Changeset{} = changeset} ->
|
|
|
|
{:noreply, assign(socket, :changeset, changeset)}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp save_property(socket, :new, property_params) do
|
2020-09-14 19:45:56 -04:00
|
|
|
current_user = socket.assigns.current_user
|
|
|
|
property_params = Map.put(property_params, "user_id", current_user.id)
|
|
|
|
|
2020-09-14 12:22:25 -04:00
|
|
|
case Properties.create_property(property_params) do
|
|
|
|
{:ok, _property} ->
|
2021-03-04 22:03:27 -05:00
|
|
|
flash = {:info, "Property created successfully"}
|
|
|
|
send(self(), {:put_flash_message, flash})
|
|
|
|
|
2021-03-03 16:07:59 -05:00
|
|
|
socket
|
|
|
|
|> push_event("modal-please-hide", %{})
|
|
|
|
|> live_noreply()
|
2020-09-14 12:22:25 -04:00
|
|
|
|
|
|
|
{:error, %Ecto.Changeset{} = changeset} ->
|
|
|
|
{:noreply, assign(socket, changeset: changeset)}
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|