简体   繁体   中英

How to have multiple, separate, instances of Trix / ActionText rich text areas on the same page?

I have a list of commentable models in my Rails view, represented by cards that each have their own comment form. The forms are identical (from the same partial), and have a rich_text_area for the commentable's body (defined as has_rich_text :body on the model, per the docs). It is close to the following (simplified) example:

<% @assignables.each do |assignables| %>
  <!-- omitted code displaying the assignable object -->

  <!-- ADD COMMENT FORM -->
  <%= form_with model: Comment.new do |form| %>
    <div class="">
      <%= form.hidden_field :commentable_id, value: assignable.id %>
      <%= form.hidden_field :commentable_type, value: assignable.class.name %>
      <%= form.rich_text_area :body, data: { controller: "mentions" } %>
      <%= form.submit "Submit", class: "button button-primary" %>
    </div>
  <% end %>
<% end %>

Only the first form on the page (in DOM order) actually submits a body parameter. Network requests from any other form shows a blank comment[body] parameter. Additionally, if I add text to the 2nd form's input, then go back and submit the first form without touching it, the submission includes the input I entered into the 2nd form.

From this, I understand I need to override some attribute which is supposed to be unique. I've scoured the Rails docs and the Trix docs, but I haven't found anything which indicates how to make Rails do this override such that Trix accepts it.

What attribute do I override, and how?

Turns out, the answer is simple: override the id attribute of the rich text area to include a unique value like a primary key, and Rails handles the rest.

Eg:

<%= form.rich_text_area :body, data: { controller: "mentions" }, 
  id: "commentable_#{commentable.id}_comment" %>

Translates to:

<form …>
  <input id="commentable_1_comment" value="Editor content goes here" type="hidden" name="content">
  <trix-editor input="commentable_1_comment"></trix-editor>
</form>

Now every instance of the text area has a unique ID (rather than the generic new_comment ) and the hidden inputs all submit their values correctly.

For reference: TheTrix documentation show what the HTML is supposed to look like at the after ERB is done with it, but the Rails rich_text_area docs don't indicate anything about attributes you might want to override.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM