Search code examples
dynamicckeditorconfigtoolbox

Dynamic ckeditor toolbar


I want to set ckeditor tool bar based on the user type and some condition.

Partialy I done as below:

switch(UserMode)
{
    case "1":
        config.toolbar_MyTool = [
            ['Find', 'SelectAll'], ['Anchor'], ['Maximize']
        ];
        break;
    case "2":
        config.toolbar_MyTool = [
            ['Find'], ['Anchor'], ['Maximize']
        ];
        break;
}

Code goes long based on the usermode so I want to create a array and just I want to assign the toolbar like as below:

config.toolbar_MyTool = myToolArray;

Also I want to check own post or other person post. If it is own post I want to add some tools additionally.


Solution

  • You would start by defining your different toolbars in the config.js

    config.toolbar_MyToolUserMode1 = [
            ['Find', 'SelectAll'], ['Anchor'], ['Maximize']
        ];
    
    config.toolbar_MyToolUserMode2 = [
            ['Find'], ['Anchor'], ['Maximize']
        ];
    

    Those toolbar-definitions can then be used later in your page, but be aware that as soon as you create an instance of CKEditor, the toolbar layout CAN NOT be changed:

    CKEDITOR.config.toolbar = "MyToolUserMode1";
    var instance = CKEDITOR.appendTo(parentElement);
    

    Solution 1:

    You would have to create a new instance to change the toolbar dynamically:

    switch(UserMode)
    {
    case "1":
        if (instance) instance.destroy();
        CKEDITOR.config.toolbar = "MyToolUserMode1";
        instance = CKEDITOR.appendTo(parentElement);
        break;
    case "2":
        if (instance) instance.destroy();
        CKEDITOR.config.toolbar = "MyToolUserMode2";
        instance = CKEDITOR.appendTo(parentElement);
        break;
    }
    

    Solution 2:

    However, if you are happy with showing the full toolbar also in usermode 2 and greying the SelectAll-Button, then the following could be your solution:

    CKEDITOR.config.toolbar = "MyToolUserMode1";
    var instance = CKEDITOR.appendTo(parentElement);
    
    switch(UserMode)
    {
    case "1":
        instance.getCommand('selectAll').enable();
        break;
    case "2":
        instance.getCommand('selectAll').disable();
        break;
    }
    

    [EDIT feb 15]

    Solution 3:

    According to your comment -> how to dynamically construct with array.push

    No configuration needed in config.js

        // your code
        var myToolbarSection1 = new Array();
        myToolbarSection1.push('Bold');
        myToolbarSection1.push('Italic');
    
        // attaching this section to toolbar
        var myToolbar = new Array();
        myToolbar.push(myToolbarSection1);
    
        // setting the toolbar
        CKEDITOR.config.toolbar_Dynamic = myToolbar;
        CKEDITOR.config.toolbar = 'Dynamic';
    
        var instance = CKEDITOR.appendTo('myDIVID');