Work around multiple FORM elements bug with Turbo

Not sure if any of you came across this issue yet, but when you are using <a href=> links to navigate with Turbo, it keeps on adding FORM elements at the bottom of the page.

For example.

<a href='/feedback/new' data-method="get">Send Feedback</a>

Click on this link will add the following tag

<form method="post" action="http://localhost:3000/feedback/new" target="" style="display: none;"><input name="_method" value="get" type="hidden"><input name="authenticity_token" value="v1UkhmdAujuI0tWj4ws5t549WOmkc9mFZu7aQeoktS0bZwt07yEKQ9QwqOZ3-sf33plwGsmdii7nXZICR4xjbA" type="hidden"><input type="submit"></form>

Click on that link again, will add another one, ad infinitum.

I am guessing it’s a bug in Turbo. It should clean up these forms.

For now here’s the work around (using jQuery for simplicity)

  $(document).on("turbo:submit-end", function(event){  
    event.detail.formSubmission.formElement.remove()
  })

I’m pretty sure it has to do with the data-method="get" attribute in the link.

I don’t think adding a data-method of get to a link is relevant, because it’s what a regular link does anyway. Try removing it.

If you want to use a different method for a link, use an inline form (or button_to if you’re using Rails).

Digging a little deeper I found out that maybe it’s Rails UJS that’s messing with links that have a data-method attribute, as seen here: https://github.com/rails/rails/blob/main/actionview/app/assets/javascripts/rails-ujs/features/method.coffee. The handleMethod function creates the form element that is later appended to the HTML body (which is what you see each time you click the link), then it calls preventDefault and stopPropagation (source code here), which is what may prevent Turbo Drive from working properly.

I have to add data-method=true because I want to trigger my new.turbo_stream.erb file. Without it, i get the text/html variant template not found error.

Using button_to doesn’t work either. I keep getting the same error.

There is general confusion surrounding data-turbo=true, data-local=true/false, how turbo_stream variant templates can be called, why links don’t work as most assume they should.

So the end result is these hacks to make things work.