I have a form that, upon submit, will store its values in a session variable before redirecting to the same form, in order to repopulate it again with the same values. This works fine for the input fields, but my select fields have their options dynamically populated by tom-select (via stimulus controller), meaning when the form is rendered, the select fields don't have options matching the value I'm trying to select, so no value gets selected. I'm trying to figure out a way around this, but so far I'm stumped. I need to somehow select the correct value after the page is rendered. I imagine I can use javascript for this, but I'm not sure the most elegant way to go about it.
So far I've tried updating it using javascript inside the html itself, making use of the tom-select api to add the value I want (api here: https://tom-select.js.org/docs/api/) That looked something like this:
<%= form.select :color, [], {}, { placeholder: "black", class: "form-select", data: { controller: 'ts--select'} } do %>
<% if session[:form_values].present? && session[:form_values]["color"].present? %>
<script>
let control = document.querySelector('#item_color').tomselect;
control.addItem('<%= session[:form_values]["color"] %>');
</script>
<% end %>
<% end %>
But this didn't work, I'm guessing because it's still rendering before tom-select can do its thing.
Any insight on this would be excellent.