6 September 2024

The example contains a CKEditor 4 widget with a dialog that allows users to edit widget properties. The dialog loads existing widget data into form fields. When the dialog is submitted, the form data is saved back into the widget element's data attribute, ensuring the widget state persists and can be reused or modified later.

Source code viewer
  1. CKEDITOR.plugins.add('myPlugin', {
  2. icons: 'myPlugin',
  3. init: function(editor) {
  4. editor.widgets.add('myWidget', {
  5. // Button and initial template
  6. button: 'Add My Widget',
  7. template: '<div class="my-widget">Content here</div>',
  8.  
  9. // Define editable areas within the widget
  10. editables: {
  11. content: {
  12. selector: '.my-widget'
  13. }
  14. },
  15.  
  16. // Allowed and required content
  17. allowedContent: 'div[!data-widget-state]',
  18. requiredContent: 'div[data-widget-state]',
  19.  
  20. // Initialization function
  21. init: function() {
  22. // Load data from `data-widget-state` into `data-cke-widget-data`
  23. this.element.setAttribute('data-cke-widget-data', this.element.getAttribute('data-widget-state'));
  24. },
  25.  
  26. // Data function to handle saving widget data
  27. data: function() {
  28. // Save data from `data-cke-widget-data` into `data-widget-state`
  29. this.element.setAttribute('data-widget-state', this.element.getAttribute('data-cke-widget-data'));
  30. }
  31. });
  32. }
  33. });
  34.  
  35. CKEDITOR.dialog.add('myDialog', function(editor) {
  36. return {
  37. title: 'Edit Widget',
  38. minWidth: 400,
  39. minHeight: 200,
  40. contents: [
  41. {
  42. id: 'tab1',
  43. label: 'Tab 1',
  44. elements: [
  45. {
  46. type: 'text',
  47. id: 'myField',
  48. label: 'My Field',
  49. setup: function(widget) {
  50. // Load saved data from widget.data, or use 'DEFAULT' as the default value.
  51. this.setValue(widget.data['FORM_ITEM_ID'] || 'DEFAULT');
  52. },
  53. commit: function(widget) {
  54. // Save form data to widget.data.
  55. widget.setData('FORM_ITEM_ID', this.getValue());
  56. }
  57. }
  58. ]
  59. }
  60. ]
  61. };
  62. });
Programming Language: Javascript