1

I want to dynamically initialize ckeditors, and later use setData() function for each one. I tried this : CKEditor 5 – get editor instances but I get error:

Cannot read property 'setData' of undefined

const editors = {}; 
function createEditor( elementId ) {
    return ClassicEditor
        .create( document.getElementById( elementId ) )
        .then( editor => {
        editors[ elementId ] = editor;
    } )
        .catch( err => console.error( err.stack ) );
}

$(document).ready( function() {
    createEditor( 'editor1' );
    createEditor( 'director1' );

    console.log(editors.editor1.setData('test')); //error message
});

Is it possible to do what I want and if yes, what should I do?

Alex
  • 23
  • 2
  • 8

2 Answers2

2

Please see: https://ckeditor.com/docs/ckeditor5/latest/api/module_core_editor_editor-Editor.html#event-ready.

You can only set editor data when it is full loaded. While there is a ready event, as you can read in a link, a much better place is the promise returned by the create method. Your code should probably look like so:

var editors = [];   
function createEditor( elementId, data ) {
    return ClassicEditor
        .create( document.querySelector( '#' + elementId ) )
        .then( editor => {
        editors[ elementId ] = editor;
        editor.setData( data ); // You should set editor data here
    } )
        .catch( err => console.error( err ) );
}

$(document).ready( function() {
    createEditor( 'editor', 'test' );
    createEditor( 'director1', 'test' );
});
j.swiderski
  • 2,405
  • 2
  • 12
  • 20
0

You can set class to every text area, e.g. ckeditor

<textarea class="ckeditor"></textarea>

Next in script section select all elements by class ckeditor and init editor for everyone

<script>
    const editors = document.querySelectorAll('.ckeditor');
    editors.forEach((el) => {
        ClassicEditor
            .create(el)
            .catch( error => {
                console.error( error );
            } );
    });
</script>
Community
  • 1
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 17 '23 at 15:55