Search code examples
ruby-on-railsrubysimple-formmedium-editor

How to implement MediumEditor gem within SimpleForm in Rails?


I want to add MediumEditor to a simple form field where users are able to write texts. There is a gem for rails but I don't know how to implement it within a simple form.. How the f.input field should look?


Solution

  • According to the MediumEditor docs, this is how to use it:

    You can now instantiate a new MediumEditor object:

    <script>var editor = new MediumEditor('.editable');</script>
    

    The above code will transform all the elements with the .editable class into HTML5 editable contents and add the medium editor toolbar to them.

    You need to reference the input element by its id or class. If you are using form_for, the id of the input element that it generates will follow the format "OBJECT_ATTRIBUTE", where OBJECT is the name of the object for which you are building the form, and ATTRIBUTE is the name of the attribute which the form field corresponds to.

    So if your form looks like this:

    <%= form_for @article do |f| %>
      <%= f.text_area :body, size: "60x12" %>
    

    the resulting html element will look like this:

      <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
    

    So you'd have to pass the id "article_body" to the MediumEditor constructor, like this:

     <script>var editor = new MediumEditor('#article_body');</script>
    

    You can also choose any arbitrary id or class for your input element passing it as an option to the form builder:

    <%= f.text_area :body, size: "60x12", id: "my-medium-editor-text-area" %>
    

    Edit: I just noticed you're using Simple Form. If you wanted to pass a custom id using simple form it would have look something like this:

      <%= f.input :article, input_html: { id: "my-medium-editor-text-area" } %>