11

Rails adds support for adding a default value to the rich text area

 3 years ago
source link: https://blog.saeloun.com/2020/09/16/add-default-value-in-trix
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Rails has added support for adding a default value to the rich text area.

To specify the default value for a rich text area, we need to pass the value in the form field, as shown below:

<%= form.rich_text_area :description, value: "Default description" %>
default_description.png

value also accepts HTML, as shown below:

<%= form.rich_text_area :description, value: "<div>First point</div><div>Second point</div>" %>
html_default.png

Technical aspect of this change:

Before

When we pass value to the rich text area, it was not set to the hidden input.

This hidden input is used by <trix-editor>.

In our case,

<%= form.rich_text_area :description, value: "<div>First point</div><div>Second point</div>" %>

used to produce the following:

<input type="hidden" name="post[description]" id="post_description_trix_input_post">
<trix-editor value="<div>First point</div><div>Second point</div>" id="post_description" input="post_description_trix_input_post" class="trix-content" data-direct-upload-url="http://localhost:3000/rails/active_storage/direct_uploads" data-blob-url-template="http://localhost:3000/rails/active_storage/blobs/:signed_id/:filename" contenteditable="" role="textbox" trix-id="1" toolbar="trix-toolbar-1"></trix-editor>

After

With the recent change, the value passed is set to the hidden input, as shown below:

<input type="hidden" name="post[description]" id="post_description_trix_input_post" value="<div>First point</div><div>Second point</div>">
<trix-editor id="post_description" input="post_description_trix_input_post" class="trix-content" data-direct-upload-url="http://localhost:3000/rails/active_storage/direct_uploads" data-blob-url-template="http://localhost:3000/rails/active_storage/blobs/redirect/:signed_id/:filename" contenteditable="" role="textbox" trix-id="1" toolbar="trix-toolbar-1"><div><!--block-->First point</div><div><!--block-->Second point</div></trix-editor>

Hence, we can see and edit the default value of the rich text area.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK