I have a form with 2 submit buttons. Save Draft and Save and Publish. I have found a solution which seems to be working but it feels lake a hack. Should I go for it or there is a better way to achieve this functionality?
You can have different submits with different value attributes in a form. I haven’t tried this but theoretically you could pattern match in the handle_event on that value to change the behavior of the submission.
I’ve had the same issue and I believe I came up with something equally hacky. Been working in production for a year though. It works by submitting an extra field alongside the form which is then parsed by the liveview controller.
app.js
// Liveview on form submit doesn't push the value for on the submit button
// This hook adds the value of the click to a field called "submittedButton"
Hooks.SetFormSubmitValue = {
mounted() {
this.el.addEventListener('click', function(evt) {
const trackingInput = document.querySelector('input[name="chart[submittedButton]"]');
trackingInput.value = evt.target.getAttribute('name');
});
}
}
The controller will either receive the param submittedButton with the value “save” or “saveas”. The hidden input is there in the form, but it gets overridden.
As I understand it, this will allow us to add name and value attributes to submit buttons, which would propagate through to params… Allowing multiple submit buttons!