Redirect back to "new" form and display "created"

Hi there.

I’m starting out with some basic Phoenix tutorials and am a little stuck with routing. I’m trying to create a basic URL shortener which allows a user to submit a URLs through a basic form. Each submission in the session will be listed below the form.

Expected user flow:

  1. User is always at the “new.html” form.
  2. User can submit form which is routed to “create” in the controller.
  3. Link is saved to database with a short hash.
  4. User is redirected back to “new” form where a ul list is updated with all the items they have added.
  5. If user leaves history is not persisted.


def new(conn, _params) do
  changeset = Resource.change_link(%Link{})
  render(conn, "new.html", changeset: changeset)

def create(conn, %{"link" => link_params}) do
    case Resource.create_link(link_params) do
      {:ok, link} ->
        |> put_flash(:info, "Link created successfully.")
        |> redirect(to: Routes.link_path(conn, :new))

      {:error, %Ecto.Changeset{} = changeset} ->
        render(conn, "new.html", changeset: changeset)

I’m struggling to see how after creation I get each of the “link” creations displayed on the “new.html” form.

Thanks for any pointers.

It seems You want to mix both index (list of links) and new (display a form). In a REST world, they would be separate actions.

But if You want both in the same action, You could do like this

def new(conn, _params) do
  links = YourContext.list_links()
  changeset = Resource.change_link(%Link{})
  render(conn, "new.html", changeset: changeset, links: links)

And render your links in the template

PS. I may not have understood You. Do You want all the links? or just the last one?

1 Like

I’m only looking to list links which the current use has submitted, rather than everything which has been added.

Wouldn’t this list everything in the database?

I get my approach may be totally wrong.

Yes, it will list all records.

Usually, in REST, You do like this…

After successful create, You are redirected to show action, with id specified…
You load the link by it’s id.

So it looks You want to mix new with show.

PS. Or You could just refactor the query to get only the user links within the day…