zubroid
zubroid

Reputation: 121

CKEditor 4 + Enhanced Image, center by default. FYI

It's not a question, but rather a solution (with a small dirty trick).

I needed to insert an image in CKEditor with "center" alignment by default. I could not find working example, so I spent lots of time and come up with the following answer.

Upvotes: 2

Views: 1187

Answers (2)

Anthony Gray
Anthony Gray

Reputation: 384

I've used the above solution for a few years successfully - although now (CKEditor Version 4.14.0) it throws an error and no longer works. After a bunch of troubleshooting and assistance from admittedly old documentation from here: https://nightly.ckeditor.com/20-05-20-06-04/standard/samples/old/dialog/dialog.html ... the following seems to work here:

In editor config.js file:

CKEDITOR.on('dialogDefinition', function(ev) {
  let dialogName       = ev.data.name;
  let dialogDefinition = ev.data.definition;
  console.log(ev);
  if (dialogName == 'image2') {
    dialogDefinition.onFocus = function() {
      /**
       * 'none' is no good for us - if is none - reset to 'center'
       * if it's already 'left','center', or 'right' - leave alone.
       */
      if (this.getContentElement('info', 'align')
          .getValue() === 'none') {
        this.getContentElement('info', 'align')
            .setValue('center');
      }
    };
  }
});

Upvotes: 2

zubroid
zubroid

Reputation: 121

In your editor's config.js

CKEDITOR.on( 'dialogDefinition', function( ev ) {
    // Take the dialog name and its definition from the event data.
    var dialogName = ev.data.name;
    var dialogDefinition = ev.data.definition;

    if ( dialogName == 'image2' ) {

        ev.data.definition.dialog.on('show', function() {
            //debugger;
            var widget = ev.data.definition.dialog.widget;
            // To prevent overwriting saved alignment
            if (widget.data['src'].length == 0)
                widget.data['align'] = 'center';

        });

    }
});

Enjoy!

Upvotes: 3

Related Questions