Implementing LiveView Form Cancel Button

Problem: I cannot distinguish between a “save” and a “cancel” click within a form.

I am trying to implement a simple form using the out-of-the box simple-form component. My intent is to collect basic information, then give the user an opportunity to save or cancel. I’ve implemented like so:

      <.simple_form for={@form} phx-submit="save">
          <:actions>
            <.button>Save</.button>

            <.button phx-click="cancel" phx-value-save={false} id="canx_button">Cancel</.button>
          </:actions>
        </.simple_form>

Both the Save/Cancel buttons trigger the phx-submit event. Ideally, I’d like both buttons in the actions slot for the simple form to preserve consistent formatting. When clicking cancel, I get the “cancel” event handler followed by the “save” event handler. The "save"event does not contain the custom button value or any identifying characteristics of the source button that I can find.

I also tried removing the phx-submit event and adding a phx-click value to the save button, but then the form information isn’t posted into the event parameters.

How can I distinguish between a “cancel” and “save” click?

Try adding the type="button" attribute to the cancel button.

From what I recall, all <button> elements will trigger a submit event in their parent form unless you add that attribute.


2 Likes

Yep, good ol’ weird HTML stuff. type="submit" is the default.

1 Like

This was definitely it. Thanks!