I have what is essentially a form with multiple pages, where there is a partial which renders the form content for each page inside of a partial that contains the header, footer, "next" button.
I need my "Next" button to respond dynamically to each page. So if the user is viewing Page 1 of the form, then I'm checking that the fields (targets) on Page 1 are not empty before enabling the "Next" button, at which point they move on to Page 2, and the next button should be disabled again until all of the fields/targets on Page 2 have been completed.
So the controller should be able to fire a function each time the page change happens, which I figured I could do by detecting when certain targets are present on the DOM. But I haven't been able to find a straightforward way to do this.
This is more or less a stripped down version of what I have
The outer wrapper:
<body data-controller="next-button">
<main>
<%= turbo_frame_tag :main, do %>
<%= yield %>
<% end %>
</main>
<%= render partial: 'application/progress_bar' %>
<% end %>
</body>
Then I also have a rails form with a text field:
<%= form.text_field :name, data: { target: "next-button.contactName"} %>
This is my controller:
export default class extends Controller {
static targets = ['contactName']
connect() {
console.log(this.contactNameTarget);
}
contactNameTargetConnected() {
console.log('foo');
}
}
When the page loads, console.log(this.contactNameTarget)
outputs the HTML for contactName as expected, but contactNameTargetConnected()
does nothing.
Based on the stimulus documentation regarding lifecycle callbacks, I would expect this function to fire on load, especially since it clearly can access this.contactNameTarget
I also looked at a posted solution from the stimulus team on github where they have an example that looks like it could solve my issue, but the code they've posted is deprecated, and I was not able to get it working:
const event = document.createEvent("CustomEvent")
event.initCustomEvent("inner-connected", true, true, null)
this.element.dispatchEvent(event)