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.

1 Answers1

1

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://stackoverflow.com/a/76112894/207090

Alex
  • 16,409
  • 6
  • 40
  • 56