New to Phoenix, need some help please! (form_for @conn VS form_for @changeset)

Hi All!

I’m new to Phoenix and Elixir, and both of these tools are great. Previously I created websites using only PHP, and played a little bit with Ruby on Rails.
Currently I am reading the Mastering Phoenix book (free) at the writer’s website, which someone shared here in the forum.
What I’m not getting is the following;
In some cases like in registeration/new.html.eex he uses something like,
<%= form_for @changeset, registration_path(@conn, :create), [as: :registration, id: "registration-form"], fn f -> %>

and in other cases he uses,
<%= form_for @conn, session_path(@conn, :create), [as: :session, id: "session-form"], fn f -> %>

Why in one place he uses <%= form_for @changeset and in another place he uses <%= form_for @conn ?

Note, I know the idea of changeset and conn upto some extent.

Thank you in advance!, and I’m sorry if this question sounds stupid!

:wave:

https://hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html might be relevant.

The author probably uses changesets when there exists some underlying entity for the action, like a new user for the registration form. And conn where there isn’t one, or it is relatively ephemeral, like a session for the login action.

Welcome to the forum!

The why is entirely dependent on the specifics of the application.

The mechanism by which this is possible is easier to explain:

Phoenix.HTML.form_for/4 relies on the “Phoenix.HTML.FormDataprotocol.

For changesets Phoenix implements the protocol via phoenix_ecto:

For Plug.Conn it is implemented right in phoenix_html:

Welcome to the Elixir community!

On the page where the login form’s template is displayed, he mentions as,