Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a newline to my input field (which is expected behaviour).
Is there a way to make submit work on pressing the Enter key without messing up the way the form is cleared after submitting?
I’m using below code to make the form work. This form works properly when the type of the input element is the default text type rather than a “textarea”.
I think you don’t need the value={@user_input_value} since you already bind field={@input_message_form[:message]}. If you get rid of the @user_input_value you can use the form itself to update the value. For proper clearing of the form it was necessary to update the form with the phx-change callback function (see How to clear a textbox after submit - #2 by andreaseriksson).
My LiveComponent looks like below, but this should also work for a LiveView:
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_form}
end
defp assign_form(socket, content \\ nil) do
assign(socket, :form, to_form(%{"content" => content}, as: "message"))
end
def handle_event("update", %{"message" => %{"content" => content}}, socket) do
# This function seems to be required for clearing the form after submitting because Phoenix LiveView
# needs to keep track of the items and can't clean properly otherwise (https://elixirforum.com/t/how-to-clear-a-textbox-after-submit/47002/2)
{:noreply,
socket
|> assign_form(content)}
end
def handle_event("save", %{"message" => message_params}, socket) do
# We don't want to handle messages here. Send them to parent and let parent
# deal with it.
send self(), {:new_message, message_params}
# Set empty form since we propagated the message to parent
{:noreply,
socket
|> assign_form}
end
def render(assigns) do
~H"""
<div>
<.form id="message-form" for={@form} phx-submit="save" phx-change="update" phx-target={@myself}>
<div class="flex-1 min-w-0">
<.input
field={@form[:content]}
placeholder="Start typing..."
autocomplete="off"
/>
</div>
<.button phx-disable-with="Submit">
Submit
</.button>
</.form>
</div>
"""
end
Maybe try making it function properly first with a regular form and then switch to a textarea by using the code suggested by @codeanpeace?
Yea that’s what I thought too, but for some reason the field attribute doesn’t populate the value inside the input. I think I’ll also switch to hooks so I can easily have the shift + enter functionality.