Home > other >  Rails simple_form element with data-... attributes for stimulus?
Rails simple_form element with data-... attributes for stimulus?

Time:08-19

I am trying to hook up a stimulus controller to a form element which is inside a form generated by the simple form gem. Whatever I do - the corresponding "data-controller" attribute doesn't appear in the final rendered page (and hence, the controller won't react)...

Here's the code in question:

<%= simple_form_for book do |f| %>
  <%= render 'shared/form_errors', form: f %>
  ...
  <%= f.association :book_format, label: false, 'data-controller': 'book-format-select' %>
  ...
< % end %>

I also tried

<%= f.association :book_format, label: false, data_controller: 'book-format-select' %>

and

<%= f.association :book_format, label: false, html: {data-controller: 'book-format-select' } %>

None of that works - the output is always the same:

<select  name="book[book_format_id]" id="book_book_format_id">

Not sure what I am doing wrong?

CodePudding user response:

You need to use input_html key

It is also possible to pass any html attribute straight to the input, by using the :input_html option

<%= f.association :book_format, label: false, input_html: { data: { controller: 'book-format-select' } } %>
  • Related