[Drupal] How to load a Drupal 7 form field with default values from CKEditor body content?

| | 2 min read

One of our client's site, which runs on Drupal 7 allows users to create envelopes based on the custom values like name, address etc submitted by the user through that Drupal website. The requirement was to load this envelope in ckeditor so that end user can edit the default values given as per their wish. So we had to load the form field with the default values given in template. We used jQuery to do this. If you are looking to know how to load a drupal 7 form field with default values from CKEDITOR body content, then read on.

Suppose you have an html like below inside CKEditor body ,

<div>
   <div class="template-message" >
     <span> Message </span>
   </div>
   <div class="template-verse" >
     <span> verse </span>
   </div>
   <div class="template-name">
     <span> name</span>
   </div>
   <div class="template-address">
    <span> address </span>
   </div>
</div>

And suppose your requirement is to load your custom form's fields with these values as default values, (Refer the below image)
default.png

You may try :

jQuery(document).ready(function($) {
  if (typeof CKEDITOR != "undefined") {
    if (CKEDITOR.instances['edit-front-value']) {
      var editorContent = CKEDITOR.instances[' edit-front-value'].getData(); // the value of ck-editor's text area is assigned to the variable.
    }
    $editorContent    = $(editorContent);
    $('#edit-message').val($('.template-message', $editorContent).text()); //sets the message field with value of template-message class
    $('#edit-verse').val($('.template-verse', $editorContent).text());  //sets the verse field with value of template-verse class
    $('#edit-name').val($('.template-name', $editorContent).text()); //sets the name field with value of template-name class
    $('#edit-address').val($('.template-address', $editorContent).text());//sets the address field with value of template-address class
 }
}

#edit-message -> id of message field

#edit-verse -> id of verse field

#edit-name -> id of name field

#edit-address -> id of address field

edit-front-value -> id of Ck editor's text area

You may try alert("some value") inside the jQuery function, to check if it is working. Hope this helps.