How to redirect from a form that is inside a turbo frame?

There was a similar question posted here that i forgot the link to it. But, basically you needed to use a Stimulus Controller to listen for the events.

When the form has validation errors, i.e status: :unprocessable_entity it will do nothing. However, if the response status is success, it visits the ur.

// form_redirect_controller.js

import { Controller } from "@hotwired/stimulus"
import * as Turbo from "@hotwired/turbo"

export default class extends Controller {
  next(event) {
    if (event.detail.success) {
      const fetchResponse = event.detail.fetchResponse

      history.pushState(
        { turbo_frame_history: true },
        "",
        fetchResponse.response.url
      )

      Turbo.visit(fetchResponse.response.url)
    }
  }
}

Wiring it up with your html

<turbo-frame id='add_user_form'>
    <form action="/group/123/add_user" method="post" data-controller='form-redirect' data-action='turbo:submit-end->form-redirect#next'>
         <!-- some validation -->
        <input type="email" name="email" />
        <input type="submit" name="Add user" />
    </form>
</turbo-frame>
3 Likes