Thursday, July 25, 2013

Creating a Simple CKEditor Plugin

To sum up, we will need the following file structure for our plugin to work:
  • ckeditor root
    • plugins
      • abbr
        • images
          • icon.png
        • plugin.js

Plugin Source Code

With the following structure ready, it is time to open the plugin.js file in a text editor and to start creating the source code of the plugin.
CKEDITOR.plugins.add( 'abbr',
{
	init: function( editor )
	{
		// Plugin logic goes here...
	}
} );
All CKEditor plugins are created by using the CKEDITOR.plugins.add function. This function should contain the plugin name ('abbr') and the plugin logic placed inside the init function that is called upon the initialization of the editor instance.

Creating an Editor Command

We want our plugin to have a dialog window, so we need to define an editor command that opens a new dialog window. To do this, we will need to use the addCommand function to register the abbrDialog command. That command opens the abbrDialog dialog that we are going to define in a moment by using the CKEDITOR.dialogCommand class.
editor.addCommand( 'abbrDialog', new CKEDITOR.dialogCommand( 'abbrDialog' ) );

Creating a Toolbar Button

The plugin dialog window is to be opened by using a toolbar button. To this end, we need to define a button that will be associated with the dialog window. The CKEditor.ui.addButton function accepts a button name ('Abbr') along with the definition of the tooltip text (label) and the button icon (icon). Note that this.path is the directory where the plugin.js file resides.
These parameters are responsible for the button presentation. To make the button actually work, we need to connect it to the plugin command name defined above by using the command parameter.
editor.ui.addButton( 'Abbr',
{
	label: 'Insert Abbreviation',
	command: 'abbrDialog',
	icon: this.path + 'images/icon.png'
} );

CKEditor Initialization

It is now time to initialize a CKEditor instance that will use the Abbreviation plugin along with its toolbar button.
To register the plugin with CKEditor, we have to add it to the extraPlugins list. We also need to enhance the toolbar definition and add the plugin button by using the toolbar parameter.
Open the page that will contain CKEditor in a text editor and insert a CKEditor instance using the following toolbar and plugin configuration.
<script type="text/javascript">
//<![CDATA[
	// Replace the <textarea id="editor1"> with a CKEditor
	// instance, using default configuration.
	CKEDITOR.replace( 'editor1',
		{
			extraPlugins : 'abbr',
			toolbar :
			[
				['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
				['About','-','Abbr']
			]
		});
//]]>
</script>
After you load the page containing the above CKEditor instance, you should be able to see the new plugin toolbar button along with its tooltip.

Plugin Dialog Window

Clicking the button should open the abbrDialog dialog window. First, however, we need to return to the Abbreviation plugin source file and define the dialog window by using the CKEDITOR.dialog.add function. To see all dialog window definition elements, refer to the CKEditor JavaScript API.
In our case we will give the dialog window a name ('abbrDialog') and use the title, minWidth, and minHeight parameters to define its title and minimum dimensions, respectively.
important note
The name selected for the dialog window is the name that appears in the addCommand function above.

Dialog Window Tabs

The dialog window should also contain some contents, so we will begin with adding two tabs along with their labels. Note that by default CKEditor also adds the standard OK and Cancel buttons.
In order to create the Abbreviation plugin dialog window along with two tabs, add the following code in the plugin.js file below the plugin toolbar button definition.
CKEDITOR.dialog.add( 'abbrDialog', function ( editor )
{
	return {
		title : 'Abbreviation Properties',
		minWidth : 400,
		minHeight : 200,
 
		contents :
		[
			{
				id : 'tab1',
				label : 'Basic Settings',
				elements :
				[
					// UI elements of the first tab	will be defined here 
				]
			},
			{
				id : 'tab2',
				label : 'Advanced Settings',
				elements :
				[
					// UI elements of the second tab will be defined here
				]
			}
		]
	};
} );
The result of this change can be seen immediately. Click the Insert Abbreviation toolbar button in order to open the newly created Abbreviation Properties dialog window containing two (empty) tabs.

Dialog Window Tabs Elements

User interface elements that can be added to a dialog window tab are defined in the elements parameter, which is an array ofCKEDITOR.dialog.uiElementDefinition objects.
The Basic Settings tab will contain two mandatory text fields (type : 'text') with the abbreviation and its explanation. Since both fields are obligatory, it is useful to add a simple validation mechanism in order to ensure that the user fills them.
The Advanced Settings tab will contain a single optional text field that allows the user to assign an id to the abbreviation element.
The code snippet presented below shows a full definition of the contents of both plugin tabs.
contents :
[
	{
		id : 'tab1',
		label : 'Basic Settings',
		elements :
		[
			{
				type : 'text',
				id : 'abbr',
				label : 'Abbreviation',
				validate : CKEDITOR.dialog.validate.notEmpty( "Abbreviation field cannot be empty" )
			},
			{
				type : 'text',
				id : 'title',
				label : 'Explanation',
				validate : CKEDITOR.dialog.validate.notEmpty( "Explanation field cannot be empty" )
			}	 
		]
	},
	{
		id : 'tab2',
		label : 'Advanced Settings',
		elements :
		[
			{
				type : 'text',
				id : 'id',
				label : 'Id'
			}
		]
	}
]
When you reload the editor instance and open the Abbreviation Properties dialog window, the Basic Settings tab will now contain two mandatory text fields.
 


Plugin Behavior

The presentation layer of the plugin is now ready, so we can define the plugin behavior to actually make it work.
The onOk method is invoked once the user accepts the changes introduced in the dialog window by clicking the OK button or pressing the Enter key on the keyboard. Since the plugin adds a new <abbr> element to the DOM tree, we can use the createElement function to create a new DOM element.
With the new DOM element created, we can now retrieve the values of the title and (optional) id fields with the getValueOf function and pass them to appropriate <abbr> element attributes by using the setAttribute function.
Finally, we will pass the text entered in the abbr text field as the contents of the <abbr> element by using the setText function.
With the contents of the <abbr> element ready, we can insert it into the document at the location of the cursor by using the insertElement function.
Add the following onOk function code to your dialog window definition, below the code that creates the contents of the dialog.
onOk : function()
{
	var dialog = this;
	var abbr = editor.document.createElement( 'abbr' );
 
	abbr.setAttribute( 'title', dialog.getValueOf( 'tab1', 'title' ) );
	abbr.setText( dialog.getValueOf( 'tab1', 'abbr' ) );
 
	var id = dialog.getValueOf( 'tab2', 'id' );
	if ( id )
		abbr.setAttribute( 'id', id );
 
	editor.insertElement( abbr );
}
important note
Please note that another way to insert HTML code into CKEditor is using the insertHtml function that adds HTML code at the location of the cursor in the document.
editor.insertHtml( '<h2>This is a sample header</h2><p>This is a sample paragraph.</p>' );

Full Source Code

To see the full contents of the plugin.js file, .
important note
You can also download the whole plugin folder inluding the icon and the fully commented source code.

Working Example

The plugin code is now ready. When you click the Insert Abbreviation toolbar button, the Abbreviation Properties dialog window will open. Fill in the obligatory Abbreviation and Explanation fields and click the OK button.
The newly added abbreviation will be inserted into the document and will be displayed using the default styling of your browser. In Firefox, for example, the abbreviation will be underlined using a dotted line and the explanation will be displayed in a tooltip.


Ckeditor : How can i make few tags like div, p, non editable

The protectedSource configuration setting is the setting of choice for that.
{Array} CKEDITOR.config.protectedSource
List of regular expressions to be executed over the input HTML, indicating code that must stay untouched.
I'm no expert on regular expressions but something like this should do the trick:
config.protectedSource.push(/[^<]*(<h1>([^<]+)<\/h1>)/g);
You can add attribute contenteditable=false to the tag. E.g.
ckeditor.insertHtml('<h1 contenteditable="false">Not editable text</h1>');

 
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.protectedSource
config.protectedSource.push( /<\?[\s\S]*?\?>/g );   // PHP code
config.protectedSource.push( /<%[\s\S]*?%>/g );   // ASP code
config.protectedSource.push( /(]+>[\s|\S]*?<\/asp:[^\>]+>)|(]+\/>)/gi );   // ASP.Net code 
            

CKEditor create plugin jquery

  • Create a folder named 'test_plugin'.
  • Create a file name 'plugin.js' under 'test_plugin' folder using following contents with level 'Content'.
  • Create a file file named 'icon.gif' under 'test_plugin' folder to show in CKEditor menu.
  • Add the following line or update if already exists: 
    • config.extraPlugins = "extra_plugin".
  • Create a CKEditor instance like following content with level "Create Instance".

LEVEL: "Content"

(function(){
    //Section 1 : Code to execute when the toolbar button is pressed
    var editorCustom;
    var a = {
        exec:function(editor){
            editorCustom = editor;
            var theSelectedText = "";
            var mySelection = editor.getSelection();

            if (CKEDITOR.env.ie) {
                mySelection.unlock(true);
                theSelectedText = mySelection.getNative().createRange().text;
            } else {
                theSelectedText = mySelection.getNative();
            }

            var my_html = "Insert when custom button clicked.";

            try {
                editorCustom.insertHtml(my_html);
            } catch (ex) {
                console.log(ex);
                var content = editorCustom.getData() + "<p>" + my_html + "</p>";
                editorCustom.setData(content);
            }
        }
    },
    //Section 2 : Create the button and add the functionality to it
    b='test_plugin';
    CKEDITOR.plugins.add(b,{
        init:function(editor){
            editor.addCommand(b,a);
            editor.ui.addButton('test_plugin',{
                label:'Test Plugin',
                icon: this.path + 'icon.gif',
                command:b
            });
        }
    });
})();

LEVEL: "Create Instance"

<script type="text/javascript">
    for (var i in CKEDITOR.instances) {
        if(CKEDITOR.instances[i]) {
            CKEDITOR.remove(CKEDITOR.instances[i]); /* REMOVE ALL CKEDITOR INSTANCE IF NEED */
        }
    }
    CKEDITOR.replace( 'text_area_id',
        {
            pasteFromWordRemoveFontStyles : false,
        fullPage : false,
            removePlugins : 'elementspath',
            height : 300,
            toolbar :
                [
                    {
                        name: 'styles',
                        items : [ 'Format','Font','FontSize' ]
                    },
                    {
                        name: 'basicstyles',
                        items : [ 'Bold','Italic','Underline','Strike', 'RemoveFormat']
                    },
                    {
                        name: 'paragraph',
                        items : [ 'NumberedList','BulletedList','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ]
                    },
                    {
                        name: 'clipboard',
                        items : [ 'Undo','Redo' ]
                    },
                    {
                        name: 'tableoperations',
                        items : [ '-', 'Table', 'TableInsertRowBefore', 'TableInsertRowAfter', 'TableRowDelete', '-',
                            'TableInsertColumnBefore', 'TableInsertColumnAfter', 'TableColumnDelete', '-', 'TableCellMerge',
                            'TableCellSplitVertical', 'TableCellSplitHorizontal', 'TableDeleteTable' ]
                    } ,
                    {
                        name: "test_plugin",
                        items: ["-", "test_plugin"]   /* THIS IS YOUR CUSTOM PLUGIN SHOW IN CKEDITOR */
                    }
                ]
        });
</script>