Is it possible to just update Rails form input field value using turbo frames?
Asked Answered
U

1

1

Let's say I have a form built with Rails form builder. It has a text field, and I want to dynamically update the input field's value using AJAX and turbo streams.

Is it possible to update the same text field's value without replacing it with a newly created text field using the text_field helper from the turbo stream view?

This Gorails tutorial has a similar use case, but he is updating the values of a select tag. So, he just updated the options of the select tag using options_for_select helper so the select field remains on the DOM as it is, while only the options are replaced.

Unfrock answered 22/7, 2023 at 12:36 Comment(1)
I'm curious why updating the field, vs. just the contents, is unacceptable?Brynhild
A
2

There is no built in way to do this, but making custom turbo stream actions is very easy:

// app/javascript/application.js

Turbo.StreamActions.update_input = function () {
  this.targetElements.forEach((target) => {
    target.value = this.templateContent.textContent
  });
};
# app/views/users/_form.html.erb

<%= form_with model: @user do |f| %>
  <%= f.text_field :name %>
  <%= f.submit %>
<% end %> 
# app/controllers/users_controller.rb

def update
  helpers.fields model: @user do |f|
    render turbo_stream: turbo_stream.action(
     :update_input, f.field_id(:name), "new value"
    )
  end
end

https://turbo.hotwired.dev/handbook/streams#custom-actions

If you need another example:
https://mcmap.net/q/1923548/-how-to-use-stimulus-and-turbo_stream-on-items-which-are-often-being-changed

Abigael answered 22/7, 2023 at 17:9 Comment(2)
Wow! that's a nice approach. Thanks a lot.Unfrock
So helpful to re-find this. I had adapted your referenced (previous) example a year ago for another use, but forgot how to do it. It's so clean. Thanks again.Scotia

© 2022 - 2024 — McMap. All rights reserved.