CKEditor insert html plugin

I wanted to be able to insert tokens using a drop down in CKEditor. I wanted tokens in brackets that would be replaced later by an application with something meaningful – so [name] for example would be replaced with a persons name.

Working this out meant trawling through the existing plugins and seeing how they were put together. Here is how I did it:

Step 1

Create a tokens folder in plugins, then save this in plugin.js.

Plugin.js:

[highlighter]

Step 2

Then to make the drop down appear you need to use the extraPugins option:

At the moment this code will work but may have problems if you try to put HTML into the value fields – it has a problem with ‘ and “. I haven’t looked into sorting it out yet, though some clever escaping may sort it out..

60 thoughts on “CKEditor insert html plugin

  1. You can add a html link by adding this: tags[0]=[“<a href=http://www.google.nl title=google>Google</a>”, “Google”, “Google”];

    Without the “. It will be added automatically. Thanks for the script.

    1. DavidAll my efforts to get more than a basic etoidr have failed so far. I have viewed the WordPress codex page link you gave me but this has not helped me fix this (after I have tried adding various params/args).Do you have wp_editor code (with params) that you can post here that outputs a full etoidr so that I can copy it & see if it works for me? I’m sorry to be a pain but it would be great if you could help me fix this and get a fully functional etoidr in my plugin (& not just a basic one). Many thanks

  2. I am confused. where do I add the code in step 2? I am initializing the editor via PHP. I tried adding it to the config.js below the CKEDITOR.editorConfig but the dropdown still did not show up on my page. Do I need to do something else with the toolbars?

  3. Not sure what you mean by resetting them.. if you want to add more tokens, just keep adding stuff to the tags array..

    tags[x]=["Something or other", "Something", "Something"];

  4. hai.. how can i add a combo,itz data from database as a plugin for ck editor. i already added a combo which contains values which i directly give in the plugin itself….

    so.. please help me to add a ck editor plugin who’s data from a database.

  5. Doing it from a database should be easy enough – where in the code it says:

    tags[0]=["[contact_name]", "Name", "Name"];

    you would instead do a loop through your result set from your database query. It depends on what database you’re using and what language you’re using on how to do it..

    As a quick (non working, shortened) example, in php you would replace the tags[x] bit with:

    <?php

    // 1) get values from database

    $SQL = "SELECT value, text, label FROM wherever";

    $result = mysql_query($SQL);

    $no=0

    while ($values = mysql_fetch_assoc($result)) {

    echo "tags[".$no."]=["".$values["value"]."", "".$values["text"]."", "".$values["label"].""];

    $no++;

    }

    ?>

  6. I am trying to add combobox same as you added for tokens. I have added ‘plugin.js’ file inside ‘/ckeditor/plugins/tokens’ as you did. I have also added following code into ‘config.js’ file:

    CKEDITOR.replace( ‘editor_id’,{

    toolbar :

    [

    [‘tokens’,’Styles’, ‘Format’, ‘Bold’, ‘Italic’],[‘Undo’,’Redo’]

    ],

    extraPlugins: ‘tokens’

    }

    );

    Still i unable to add dropdown for tokens into toolbox of my editor. Please suggest.

    Thanks in advance,

    Ravi.

  7. you’ve just save me, this is what i’ve been looking for, i did it but it was awful ’cause i made it with a dialog box and links inside it that were inserted in the content

  8. This example worked really well but there is one I’d like to add. If you don’t create the css and put this line in then nothing will show up.

    html.cke_skin_kama_container{visibility:visible;}

  9. This is a great tutorial! I have managed to add a combo box following your example. Now what I want to do is, based on a users selection, populate another combo box in my editor. How can I reference the second combobox in the onclick event of the first combobox?

  10. This post helped a lot in creating custom combo box in my editor. Now my issue is that combo taking size as 7 by default. I have only 5 items in combo box. I want to set the size of combo box as 5. Please advice.

  11. Here’s a simplified version of Tim’s dynamic combo box functionality, make sure you remove the tags array declarations further down in plugin.js:

    [code]

    var tags = [];

    var i = 0;

    $.ajax({

    url: "[ajax source file location]",

    cache: false,

    dataType: ‘json’,

    success: function(result){

    $.each(result, function(x, obj){

    tags[i] = [‘[‘+obj.tokenVal+’]’, obj.tokenDsp, obj.tokenDesc];

    i++;

    });

    }

    });

    [/code]

    The source JSON array looks like this:

    [code]

    [

    {

    "tokenVal": "foo1",

    "tokenDsp": "bar1",

    "tokenDesc": "baz1"

    },

    {

    "tokenVal": "foo2",

    "tokenDsp": "bar2",

    "tokenDesc": "baz2"

    },

    {

    "tokenVal": "foo3",

    "tokenDsp": "bar3",

    "tokenDesc": "baz3"

    }

    ]

    [/code]

    Thanks to Tim for providing the original code.

  12. Kuba,

    This is a great plugin. Exactly what I needed.

    I too am having the same issue as Chris where only one instance shows up when created a new one. I have changed all the tags to something different.

    Any ideas?

    Thanks in advance

  13. Hi Twitch,

    Do you mean using two versions of the plugin in the same editor? Should work if you create a new folder, change the names etc?

  14. if you please can you put for us HTML page and FCKEditor that contains tokens.

    Becuase i am trying to add one but without showing it up into Editor. i follow the needed step1 + step2.

  15. I’m having the same problem with version 4. The css file isn’t found. I’m using the kama skin. Another problem is the dropdown doesn’t stay opened.

  16. I fixed the css problem. I’m not sure if I fixed correctly but here’s what worked for me.

    I changed the css line from this:

    css : [ config.contentsCss, CKEDITOR.getUrl( editor.skinPath + ‘editor.css’ ) ],

    to

    css : [ config.contentsCss, CKEDITOR.getUrl(CKEDITOR.skinName.split(",")[1]||"skins/"+CKEDITOR.skinName.split(",")[0]+"/") + "editor.css" ],

    Also, the dropdown will stay open if you don’t click on the down arrow.

  17. Hi there!

    Thanks for this fine tutorial.

    Can I insert <img> or <a> like <div> you did ? How can I do that?

    Like:

    <a href=_quote_#_quote_ class=_quote_foo bar_quote_>hi there!</a>

    and adding,

    editor.insertHtml(value.replace(/_quote_/g, "’"));

    Thanks in advance.

  18. Hi all,

    To make contents of dropdown list dynamic I’ve done the following things:

    1) Add extra option to CKEditor that is going to be available for plug-ins

    CKEditor.config.ExtraOptions["tokens_JSON"] = … your JSON goes here (this can be as per suggestion by March 31st 2012 – Ablitica )

    2) On addRichCombo init put the following code:

    init: function()

    {

    var combo = this;

    combo.startGroup("Tokens");

    $.each(config.tokens_JSON, function(x, obj)

    {

    combo.add(obj.tokenVal, obj.tokenDsp, obj.tokenDesc);

    });

    },

    3) I’ve added additional check to make sure that tokens_JSON parameter is set. This goes to line 8 of the original source code:

    if (config.tokens_JSON === undefined)

    {

    alert(‘tokens_JSON parameter is not specified’);

    return;

    }

    Array of tags is redundant now.

    I’ve tried generating Json by handler file (.NET) and it worked just fine. But if find this approach easier to maintain.

    1. Hi DavidThanks for your helpful reply & I now have your pgulin pgulin-options-starter-kit & will take a look.One issue I have with the output from this tutorial is that in my theme options page I am not getting all the buttons or the visual & html tabs on the editors (the buttons I get I think are the quick tag buttons only eg there is no list/style/kitchen sink/text format etc buttons).Do you have any idea why I don’t get the full set of buttons & not the tabs either?

  19. thank’s for sharing. Works for me.

    For php users, here is the code to ad the button to the editor :

    $oFCKeditor = new CKEditor();

    $oFCKeditor->basePath = "../ckeditor/" ;

    $config = array();

    $config['width'] = 650;

    $config['height'] = 1000;

    $config['toolbarCanCollapse'] = false;

    $config['removePlugins'] = 'elementspath';

    $config['FullPage'] = true;

    $config['extraPlugins'] = 'tokens';

    $config['toolbar'] = array(

    ..your arrays,

    array('tokens'));

    Best regards

  20. This script helps me a lot, but I’m stucked with creating richcombo with

    multiple classnames. For example, when I add this tag;

    tags[0]=["<div class=foo bar>hi there!</div>", "Name", "Name"];

    class:bar couldn’t be added on the div and class:foo alone is attached.

    It seems that whitespace after class attribute is not recognized,

    and neither escaping( ) nor quotation("foo bar") don’t work.

    Does anybody know some workarounds for this problem? THX for advance.

  21. Hmm – I have come up with a workaround.

    tags[0]=["<div class=_quote_foo bar_quote_>hi there!</div>", "Name", "Name"];

    Note the _quote_ around "foo bar"

    then replace:

    editor.insertHtml(value);

    with

    editor.insertHtml(value.replace(/_quote_/g, "’"));

  22. I’m trying to use several instances of this plugin in one text-area. Therefore I installed the plugin in different directories and gave them different names. But only the last one is being displayed. Seems that the variables of other instances are overwritten. Is there a possibility to make that work?

    Thanks in advance

  23. Hi,

    Is there a way to keep the label of the combo unchanged after making the selection? I mean if you click on "contact_name" it should keep the "Inset tokens" label and not change it to "contact_name". Thanks!

    1. I’m afraid I haven’t time right now to dive into spcfieics, but if you can’t see the visual/html tabs or all the visual tinymce buttons then it is probably some theme/Plugin code that is causing the issue.Try setting up a clean local copy of WordPress and try the Plugin there. You will see it contains all the buttons, plus visual/html tabs.

  24. Hi, I’m using C# in .NET MVC and javascript and I need to give tag values from a database. Is there any way to do this? Does any one can help me?

    Best regards

  25. Suggestions on how you might externally in the routine invoking the editor add the tags dynamically? I have a situation where depending on wher the editor is called, the tags are completely different

  26. I am not even been able to display the button on the toolbar 🙁

    and i always find this error to come in the "error console" of firefox and even the ckeditor textarea does not show… its causing problems when i use ur STEP 2 code in which it has

    extraPlugins: ‘tokens’

    when i remove this the ckeditor is displayed but with no changes (default toolbar) ??

    what am i doing wrong.. plz do let me know as soon as possible …

    Error: uncaught exception: [CKEDITOR.resourceManager.load] Resource name "tokens" was not found at "http://legal.com/includes/ckeditor/plugins/tokens/plugin.js?t=A4SD49Y&quot;.

  27. **** sorry my last post was a little mistyped ****

    I am not even been able to display the button on the toolbar 🙁 and i always find this error

    Error: uncaught exception: [CKEDITOR.resourceManager.load] Resource name "tokens" was not found at "http://legal.com/includes/ckeditor/plugins/tokens/plugin.js?t=A4SD49Y&quot;.

    to come in the "error console" of firefox and even the ckeditor textarea does not show… its causing problems when i use ur STEP 2 code in which it has

    extraPlugins: ‘tokens’

    when i remove this the ckeditor is displayed but with no changes (default toolbar) ??

    what am i doing wrong.. plz do let me know as soon as possible …

  28. THANK YOU! This saved me hours/if not days of work! For those looking to reset the label I figured this out thanks to digging into the VerticalResponse source code since they do essentially the exact same thing for what they call merge fields.

    @great!/@Ronz — to reset the label add the onRender function just below the onClick function of plugin.js

    [code]

    onRender: function(){

    editor.on(‘selectionChange’, function(ev){

    this.setValue(”);

    }, this);

    }

    [/code]

    Does anyone know how to put the label inside the drop down instead of the left side?

  29. <pre>

    /* put this inside the init function as an example of how to dynamically populate the combo box with options from a jquery ajax call (coldfusion cfc in my case). Could be any json array as the source.

    //store this into var since won’t be available in success of Ajax call

    var theUICombo = this;

    //access the ID of the orginal textarea incase you want to attach data like i have storing categories of tokens to load to pass into my ajax call so i can limit what tokens are available to certain editors throughout the app.

    var $theRootEl = $("#" + editor.element.id);

    //fetch my token categories

    var tokenCats = $theRootEl.data(‘tokenCats’);

    $.ajax({

    url: "cfc/placeholders/placeholdersGateway.cfc?method=get&returnformat=json&returnArray=1",

    data: {

    ColList: "PlaceholderVar",

    PlaceholderCats: tokenCats

    },

    cache: false,

    dataType: ‘json’,

    success: function(result){

    //eventually will loop over my token categories and make optgroups that way

    theUICombo.startGroup("Tokens");

    $.each(result, function(x, obj){

    theUICombo.add(obj.tokenVal, obj.tokenDsp, obj.tokenDesc);

    });

    }

    });

    </pre>

  30. Hi, thank you.

    I’m use this text inside the init function:

    var _this = this;

    $.post(‘/categ/get-tokens’, {data: 12}, function(response){

    Data = response;

    _this.add(‘foo’, ‘foo’, ‘foo’);

    });

    But it’s not work, when I click on my Combo, firebag says:

    [X] doc.getById(items[value]) is null

    [Break on this error] doc.getById( items[ value ] ).removeClass( ‘cke_selected’ );

  31. Hi Kuba,

    Thanks so much for the reply. Sorry I haven’t been able to come back and check for a response. I actually realized what I was doing wrong when I was typing a description of how it wasn’t functioning. I had the extrPlugin syntax incorrect for multiple instances.

    Instead of:

    config.extraPlugins = ‘layouts,content’;

    I had:

    config.extraPlugins = ‘content,’

    config.extraPlugins = ‘layouts’;

  32. I have added the first part of the code to a new plugins.js file which I have created in ckeditorplugins okensplugins.js. I have tried the second part of the code to config.js and tokensplugins.js but its not showing at all. Please advice

Leave a Reply

Your email address will not be published.