saveman71
Why does <.form> discard method and CSRF token when :action is absent, and is action="" a reliable way to submit to the current URL?
Hello !
We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id), so that changeset error re-renders keep the browser URL stable: F5 reloads the form instead of GET-ing the index/show URL, and our URL matching JS bundle loading keeps working without hacks.
This has been a recurring source of issues on our end so we’re currently writing an internal guide/credo check to enforce that.
Regarding the form target, in plain HTML you’d get this for free by omitting action: the form then submits to the current URL.
But Phoenix.Component.form/1 explicitly discards method and the CSRF token in that case (docs).
Today we pass the page’s own URL explicitly:
<.form for={@form} action={~p"/things/#{@thing}/edit"} method="put">
That works, but means that a template shared between new and edit has to conditionally rebuild the URL the browser is already on, adding extra steps to check and maintain.
Two questions:
- Is there a reason for discarding
method/csrf_tokenwhen:actionis absent for dead views? action=""seems to work as a “submit to current URL”: HTML treats an empty action as the document’s URL, and it’s truthy so the component rendersmethodand the CSRF token. Is that supported behavior we can rely on?
A side effect is that it’s going to call Plug.CSRFProtection.get_csrf_token_for(""), which returns a valid token but unscoped as far as I understand. Is this bad?
Thanks in advance for any insight.
Most Liked
LostKobrakai
nseaSeb
<.form for={@form} action="" method={if @thing, do: "put", else: "post"}>
It guess in this case “” is truthy in Elixir, so <.form> takes the “action provided” branch and normally generates the hidden _method field and the CSRF token.
Maybe send the URL by another approach ?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









