Toggling between showing display text and edit text with Phoenix forms

Hello, I am trying to display some text and allow the user to edit it. Or if there’s no text, just an input form.

Currently my code is just the input form and looks like this.

  <%= form_for @changeset, Routes.text_path(@conn, :update, @text), fn f -> %>
    <div>
      <%= label f, :text, "Text" %>
      <%= text_input f, :text, required: true %>
    </div>
    <div>
      <%= submit "Update" %>
    </div>
    <% end %>

How do I toggle between display and if user clicks “EDIT”, it shows them the input form with the data that is currently in the database pre-populated in the edit form?

I hope I understand you question correctly here:

If the changeset is already persisted, you want to update, otherwise you want to create?
Take a look at the generated html when using mix phx.gen.html It’s a great start if you don’t understand how to use the framework yet!

Ona sidenote: no matter what, you should not use Routes.text_path(@conn, :update, @text) that would put the text into the URL.

As suggested above, simply run this command in a toy project: mix phx.gen.html Accounts User users text:string

Add the following to your router’s main scope /:

resources "/users", UserController

Then check the the CRUD template in lib/app_web/templates/user/show.html.eex. There it displays the model and there’s also an Edit button that will take you to a pre-populated edit form.

Check the show and edit functions in lib/app_web/controllers/user_controller.ex

1 Like