Sorry for yet another question about redirecting from form submissions, but I’ve tried everything I can find in previous answers and I’m still not able to make this work. I’m trying to have a form which redirects on successful submission, but only updates parts of the page on failure (the part with the form).
Using a turbo-frame, I can get the latter working but the browser then doesn’t follow redirects. I can add target=’_top’ which fixes redirects, but then invalid form submissions redraw the entire page, not just the form.
I’ve created an example app here: GitHub - aa365/turbo-test . The code in question lives in app/views/widgets and widgets_controller.rb
I saw you controller and seems that you’re not responding to turbo_stream format in any of the create, update and destroy actions. Remember that turbo set turbo_stream as the default format for those actions. So you can try to add the format.turbo_stream { redirect_to ... } in those actions and check if that works.
I’m in the same boat. According to the Handbook, Turbo is supposed to follow a 303 redirect. I’m finding that it is following the redirect but it’s not rendering it. Some of the Turbo events indicate that Turbo is perfectly aware of the response being a redirect but just doesn’t render the response.
This is incredibly dumb and I don’t recommend anyone use this, but I’ve got the client behaving mostly as expected with this JS shim:
document.addEventListener("turbo:before-fetch-response", function(event) {
if (typeof (event.detail.fetchResponse) !== 'undefined') {
var response = event.detail.fetchResponse.response
if (response.redirected) {
event.preventDefault()
Turbo.visit(response.url)
}
}
})
It doesn’t seem to be the right event to prevent the request so it ends up requesting the redirect URL once as turbostream and again as HTML. The turbostream response is ignored, but the html request made with Turbo.visit works.