Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ckeditor replace textarea using class name with different toolbar confogurations

Tags:

ckeditor

I am using the following code to add ckeditor to my pages.

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

I would like to define a few toolbar configurations as not all of the textareas in my application need a full toolbar. I have customized the default toolbar configuration for my needs, but would like to break this down even further to a more basic toolbar for some of my textareas.

Is there a way to do this if I am using the class attribute to set ckeditor?

like image 212
Stephen Avatar asked Nov 03 '22 18:11

Stephen


1 Answers

It's not possible to have different configurations for editors created by class name. In such case, only the global CKEDITOR.config is considered.

Still there's easy workaround for this problem. First, put this script in the top of the document:

<script>
    CKEDITOR.replaceClass = null; // Disable replacing by class
</script>

Now define the data-custom-config property (as config.customConfig) for each <textarea> you want to replace like this:

<textarea class="ckeditor" data-custom-config="myCustomConfig.js">
    Moo
</textarea>

Finally use the following code to manually replace editors by class name (assuming your class is ckeditor). This code will replace all textareas of the class ckeditor with CKEditor instance driven by the config defined in data-custom-config attribute:

var textareas = Array.prototype.slice.call( document.getElementsByClassName( 'ckeditor' ) ),
    textarea, cfg, customCfg;

while ( ( textarea = textareas.pop() ) ) {
    textarea = new CKEDITOR.dom.element( textarea );
    cfg = {};

    if ( ( customCfg = textarea.getAttribute( 'data-custom-config' ) ) )
       cfg[ 'customConfig' ] = customCfg;

    CKEDITOR.replace( textarea.getId(), cfg )
}

And now comes the cherry on the top. Put your custom toolbar config in myCustomConfig.js:

CKEDITOR.editorConfig = function( config ) {
    config.toolbar = [
        { name: 'basicstyles', items: [ 'Bold', 'Italic' ] }
    ];
};

Of course you can modify this code to involve jQuery for easier element selection, use some object literal instead of config.customConfig and so on. This is just a showcase of how the problem can be solved.

like image 55
oleq Avatar answered Nov 13 '22 04:11

oleq