Hi ,I am trying to create a html.heex file within live folder I want to create a form and post it data to my .ex file
But not able to resolve this.
It would be very helpful to have form tag explaination with example
Hi ,I am trying to create a html.heex file within live folder I want to create a form and post it data to my .ex file
But not able to resolve this.
It would be very helpful to have form tag explaination with example
Generally you will start with an empty changeset for your schema, saving it into the socket assigns in mount/3
:
def mount(_, _, socket) do
changeset = User.changeset(%User{})
{:ok, assign(socket, changeset: changeset)}
end
Then you can use the .form
helper with that changeset (in the .html.heex
):
<.form let={f} for={@changeset} phx_submit="action_name">
<%= text_input f, :name %>
<%= text_input f, :address %>
<%= text_input f, :any_other_field_in_the_schema %>
<%= submit "Submit Button Text Here" %>
</.form>
The f
represents the form itself, and will be passed as the first argument to your inputs. The "action_name"
will be used by the event handler in your LiveView:
def handle_event("action_name", %{"user" => params}, socket) do
case Accounts.register_user(params) do
{:ok, user} ->
...
{:noreply, socket}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
The second argument %{"user" => params}
is the form data (as strings) e.g.
%{
"user" => %{
"name" => "test name",
"address" => "123 Fake St",
"any_other_field_in_the_schema" => "sample"
}
}
Docs for reference: Phoenix.HTML.Form — Phoenix.HTML v3.2.0
And if you want labels or error messages attached to a field, you can use helpers for that too:
<%= label f, :name %>
<%= text_input f, :name %>
<%= error_tag f, :name %>
The error_tag will display any errors from the changeset when the user enters invalid data.
If you want the errors to display “live” (before the submit button is pressed), you can use live validation like
<.form let={f} for={@changeset} phx_submit="action_name" phx_change="validate">
Where "validate"
goes to another event handler which updates the changeset:
def handle_event("validate", %{"user" => params}, socket) do
changeset =
%User{}
|> User.changeset(params)
|> Map.put(:action, :insert)
{:noreply, assign(socket, changeset: changeset)}
end
Thanx for the reply ,but i am still stuck
def mount(%{“rid” => roomid}, _session, socket) do
{:ok, assign(socket, room: roomid)}
end
I have room ID which i also had to pass to html.heex
for ref :Let’s Build a Real Time Chat Application with Elixir and Phoenix - YouTube
I am using this video to create a live view chat application ,if possible please see this video from 27 min onward
import Phoenix.LiveView.Helpers
Welcome to Phoenix Room => <%= @room %>
<.form let={f} for={@changeset} phx_submit=“action_name”>
<%= text_input f, :Message %>
<%= submit “Submit Button Text Here” %>
</.form>