How does form_for infer the function to use based on the controller method?

I have a form that I’m trying to render the same way for the new action as it is for the update action via

<%= render “form.html”, changeset: @changeset, action: post_path(@conn, :update, @post) %>

I’m using this in both new.html.exs and update.html.exs (“note the :update in the post_path”)

The issue I’m having is that some how the form_for is inferring which method the form should use by rendering a hidden input of <input name="_method" type="hidden" value="put"> for only the update.html.exs but not the new.html.exs

When looking at the form_for itself there is nothing indicating how it knows when to generate the hiden form input or not.

<%= form_for @changeset, @action, fn f -> %>

The action in this case is just the path of the post_path, but nothing is specifying which method should be used.

I understand that I can supply a method option to the form_for, but my question is how does it infer it if nothing is given?

1 Like

I think it maybe coming from the changeset.

1 Like

I think it maybe coming from the changeset.

I think you are right.

It’s also worth checking out Phoenix.HTML.FormData and Phoenix.HTML.Form modules.

3 Likes

In case others come here via search; there is a very informative thread here…

4 Likes