Using an user resource as example, the URL for creating a new user is /users/new.
If I submit the form with empty fields, the page is rendered again showing the errors, however the URL is now /users instead of /users/new
Is this by design?
Using an user resource as example, the URL for creating a new user is /users/new.
If I submit the form with empty fields, the page is rendered again showing the errors, however the URL is now /users instead of /users/new
Is this by design?
TL;DR: This has nothing to do with Phoenix, skip the explanation below if you understand how Phoenix works and just read: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
First let’s look at your generated routes with phx.routes
:
users_path GET /users MyappWeb.UsersController :index
users_path GET /users/:id/edit MyappWeb.UsersController :edit
users_path GET /users/new MyappWeb.UsersController :new
users_path GET /users/:id MyappWeb.UsersController :show
users_path POST /users MyappWeb.UsersController :create
users_path PATCH /users/:id MyappWeb.UsersController :update
PUT /users/:id MyappWeb.UsersController :update
users_path DELETE /users/:id MyappWeb.UsersController :delete
As you can see, /users/new
only accepts a GET request (the form that an user will fill with data). Ok, now look at your new.html.eex
file:
<%= render "form.html", Map.put(assigns, :action, Routes.users_path(@conn, :create)) %>
The code above defines the route where the form will send the request (:create
), if you look at your routes again, you’ll notice that the :create
action corresponds to a POST request to the /users
route. That explains why the application points to the /users
route when you submit the form.
To understand how action works, read this article, specifically read about the POST method: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
Than you for your response. I was confused because I saw the form in the browser and expected to see a matching URL.
Just to drive home the point, you are rendering the page from the create
action, not redirecting or sending a new request. It’s still the same post
request that tried to create the resource.