I've got a form with 2 buttons:
<form method="POST" class="pt-10"><div class="flex flex-row pt-10"><button type="submit" name="save-and-exit" class="btn btn-primary btn-lg">{ mode == "new" ? "Save and Exit" : "Update and Exit" }</button></div><div class="flex flex-row pt-10"><button type="submit" name="add-tracks" class="btn btn-primary btn-lg">{ "-> Tracks" }</button></div></form>
Omitting the fields in form for simplicity.
My action looks like this:
export const actions = { default: async ({ request, fetch }) => { // create API instance const recordAPI = new RecordAPI(fetch); // retrieve the data from the form const data = Object.fromEntries(await request.formData()); // validate data and create DTO const record = recordDTO(data); // if errors returned from building the DTO (validation errors) then return the object. if (record?.errors && !emptyObject(record.errors)) { return {"data": record.data,"errors": record.errors, }; } // save the data const response = await recordAPI.post(record); if (response.status == 200) { throw redirect(302, '/records') } return { data: record,"errors": response.errors, }}
In the action
function, is there a way to know which of the 2 buttons was the one that submitted the form? I need to know this since the flow is gonna be different depending on that.
One solution I can think of is updating the form to something like this:
<form method="POST" bind:this={formElement}>
then manually append the name of the button to the form and trigger formElement.requestSubmit()
, but I was wondering if there's a way to do it directly in the action
, I believe it looks more 'elegant'.
Thanks.