Search navigation with Turbo

Thanks jacob, however I do not think that this addresses my problem. My problem is that when the user visits a link from my search results (with turbo-frame = “_top”) and then go back, my form is cleared, only the frame restores from cache. However, I have come up with a bit of a hack that seems to work okay so far. Basically I get the src of the turbo-frame, parse the url params and set the form values accordingly.

My view now looks like this:

<div data-controller="form">

  <%= search_form_for @q, :data => { turbo_frame: 'cocktail_list', form_target: 'form' } do |f| %>
    <!-- Search form with text search and js daterange picker -->
  <% end %>

  <turbo-frame id="cocktail_list" data-form-target="frame">
    <!-- Table for cocktails with sorting, pagination and link to cocktail -->
  </turbo-frame>

</div>

And my stimulus controller:

import { Controller } from "stimulus"

export default class extends Controller {
    static targets = [ "form", "frame" ]

    connect() {
        // Set frame parameter values if applicable
        let src = this.frameTarget.getAttribute("src")
        if(src) {
            let query = unescape(src.slice(src.indexOf('?') + 1))
            const searchParams = new URLSearchParams(query)

            for (let p of searchParams) {
                let formElement = this.formTarget.elements[p[0]]
                if(typeof(formElement) != 'undefined' && formElement != null) {
                    formElement.value = p[1]
                }
            }
        }
    }

    update(event) {
        this.formTarget.requestSubmit()
    }
}

Not exactly the prettiest solution, so would still love to hear how others have accomplished something like this. This post addresses the same issue but I have not been able to get data-turbo-permanent to work for this.

1 Like