Last active
November 17, 2021 14:21
-
-
Save ivanhercaz/57abe425b540c9158cf745c7e8b9d5d4 to your computer and use it in GitHub Desktop.
Replace AlpineJS click-show using LiveView assigns on a form component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppWeb.ExampleLive.FormComponent do | |
use AppWeb, :live_component | |
alias App.Examples | |
@impl true | |
def update(%{example: example} = assigns, socket) do | |
changeset = Examples.change_example(example) | |
{:ok, | |
socket | |
|> assign(assigns) | |
|> assign(:changeset, changeset) | |
|> assign(:help_message_state, example.has_help_message)} | |
end | |
@impl true | |
def handle_event("validate", %{"example" => example_params}, socket) do | |
changeset = | |
socket.assigns.example | |
|> Examples.change_example(example_params) | |
|> Map.put(:action, :validate) | |
has_help_message = case changeset do | |
%{changes: %{has_help_message: has_help_message}} -> has_help_message | |
%{changes: %{}} -> example["has_help_message"] | |
_ -> false | |
end | |
{:noreply, socket | |
|> assign(:changeset, changeset) | |
|> assign(:help_message_state, has_help_message) | |
} | |
end | |
# ... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2><%= @title %></h2> | |
<%= f = form_for @changeset, "#", | |
id: "example-form", | |
phx_target: @myself, | |
phx_change: "validate", | |
phx_submit: "save" %> | |
<div> | |
<%= if @help_message_state do %> | |
<div> | |
<%= label f, :help_message_mode %> | |
<%= select f, :help_message_mode %> | |
<%= error_tag f, :help_message_mode %> | |
</div> | |
<div> | |
<%= label f, :help_message %> | |
<%= text_input f, :help_message %> | |
<%= error_tag f, :help_message %> | |
</div> | |
<% end %> | |
</div> | |
<%= submit gettext("Guardar"), phx_disable_with: "Guardando..."%> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment