CKEditor5 insert non-editable text in the editor - ckeditor

I am trying to insert small pieces of text in the CKEditor5, like
{{ variable name }}
These variables shall not be edited by user. I tried to insert
content = '<span contenteditable="false">' + content + '</span>';
Using the following code, content is the non-editable string
content = '<span contenteditable="false">' + content + '</span>';
const viewFragment = this.editor.data.processor.toView( content );
const modelFragment = this.editor.data.toModel( viewFragment );
this.editor.model.insertContent( modelFragment );
It does not work. The wrapping part is always removed by CKEditor. What should I do to achieve this?

you should configure editor to allow for other tags
and you need html Editing plugin (sorry I forgot the real name of it)
public config = {
placeholder: 'content here',
htmlSupport: {
allow: [
{
name: /.*/,
attributes: true,
classes: true,
styles: true
}
]
}
}

Related

Using a parameter in Kendo ui template of checkboxes in TreeViewOptions

I am trying to create a class that create a generic kendo TreeView that the tree can have items with checkbox and items without checkbox.
So, I created a class with the flowing c'tor:
constructor(checkable: boolean = false) {
// Create the treeview options
const treeViewOptions: kendo.ui.TreeViewOptions = {
checkboxes: {
checkChildren: true,
template: "# if (item.level() > 0) { #" +
"<input type='checkbox' #= item.checked ? 'checked' : '' #>" +
"# } #"
},
// ... The rest of the treeViewOptions ...
}
Now, all items that their item.level==0 are without checkbox.
I want that if the parameter "checkable" of the c'tor is false, than all the items in the tree will not have checkboxes. I didn't know how to pass the "checkable" parameter into the template. I wanted something like this:
checkboxes: {
checkChildren: true,
template: "# if (checkable && item.level() > 0) { #" +
"<input type='checkbox' #= item.checked ? 'checked' : '' #>" +
"# } #"
},
Please help me with that and if you think that there is more elegant way to do that I will be happy to hear.
Thanks
You could make the template be an anonymous function and have it emit different template strings depending on constructor argument.
template: function () {
if (checkable) {
return ... template string that allows checkboxes at item level > 0 ...
} else {
return ... simpler template string that has no checkboxes anywhere ...
}
}

Programmatically Add Existing File to Dropzone

I'm trying to add an existing image to my dropzone programmatically, using the dropzone.js FAQ as a guide:
// Add the existing image if it's there.
// headerDropzone is my dropzone (debug shows it as existing and initialized at this point.
var on_load_header = $( '[name="on_load_header_image"]' ).val();
var on_load_header_path = $( '[name="on_load_header_image_path"]' ).val();
if ( on_load_header ) {
// Hardcoded size value is just for testing, see my second question below.
var on_load_header_data = { name: on_load_header, size: 12345 };
// Call the default addedfile event handler
headerDropzone.options.addedfile.call( headerDropzone, on_load_header_data );
// And optionally show the thumbnail of the file:
headerDropzone.options. thumbnail.call( headerDropzone, on_load_header_data, on_load_header_path);
}
My first problem is that this is just not working. The addedfile event doesn't fire (or at least the addedfile handler in headerDropzone never fires), same goes for thumbnail.
My second problem/question is: do I have to provide the file size? I could get it server side, but I'd rather not do it if I don't actually need to.
If you need to add multiple existing files into Dropzone, declare your existing files as array and then add it into Dropzone programmatically inside a loop like so...
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#myDropzone", {
url: "/file/post",
maxFileSize: 50,
acceptedFiles: ".pdf",
addRemoveLinks: true,
//more dropzone options here
});
//Add existing files into dropzone
var existingFiles = [
{ name: "Filename 1.pdf", size: 12345678 },
{ name: "Filename 2.pdf", size: 12345678 },
{ name: "Filename 3.pdf", size: 12345678 },
{ name: "Filename 4.pdf", size: 12345678 },
{ name: "Filename 5.pdf", size: 12345678 }
];
for (i = 0; i < existingFiles.length; i++) {
myDropzone.emit("addedfile", existingFiles[i]);
//myDropzone.emit("thumbnail", existingFiles[i], "/image/url");
myDropzone.emit("complete", existingFiles[i]);
}
The Dropzone FAQ leaves out important settings required to properly preload a dropzone with (an) existing file(s).
My init method for my dropzone:
Dropzone.options.MyDropZoneID = {
...
init: function () {
var mockFile = { name: fileName, size: fileSize, type: fileMimeType, serverID: 0, accepted: true }; // use actual id server uses to identify the file (e.g. DB unique identifier)
this.emit("addedfile", mockFile);
this.createThumbnailFromUrl(mockFile, fileUrl);
this.emit("success", mockFile);
this.emit("complete", mockFile);
this.files.push(mockFile);
...
I don't know if the above is a perfect implementation, but it is working correctly with the maxFiles setting. Which is very important if you don't want buggy behavior (like the default message displaying when it shouldn't or extra files getting uploaded). You definitely need to set the accepted property to true and add the file to the files property. The only thing that I think is not required is emitting the success. I haven't played around with that enough though to know for sure.
Note: I used the following NuGet package:
Created by: Matias Meno
Id: dropzone
Version: 4.2.0
See if the functions headerDropzone.options.addedfile and headerDropzone.options.thumbnail are actually defined. It should work the way you did it, but without further info it's difficult to tell what's wrong.
About the filesize: No, it's not necessary to actually provide the accurate filesize. It's just that Dropzone automatically displays the filesize. If you don't care if some false filesize is displayed then you can just provide some random number or 0. Otherwise you might want to hide the filesize with CSS, or with JS after you add it. (The element in question has the class dz-size.
The JavaScript version of it would look something like this:
var fileSizeElement = on_load_header_data.previewElement.querySelector(".dz-size");
fileSizeElement.parentNode.removeChild(fileSizeElement);
This is now answered in official FAQ
Dropzone.options.myDropzone = {
init: function() {
let myDropzone = this;
// If you only have access to the original image sizes on your server,
// and want to resize them in the browser:
let mockFile = { name: "Filename 2", size: 12345 };
myDropzone.displayExistingFile(mockFile, "https://i.picsum.photos/id/959/600/600.jpg");
// If the thumbnail is already in the right size on your server:
let mockFile = { name: "Filename", size: 12345 };
let callback = null; // Optional callback when it's done
let crossOrigin = null; // Added to the `img` tag for crossOrigin handling
let resizeThumbnail = false; // Tells Dropzone whether it should resize the image first
myDropzone.displayExistingFile(mockFile, "https://i.picsum.photos /id/959/120/120.jpg", callback, crossOrigin, resizeThumbnail);
myDropzone.files.push(mockFile); // line missing in official docs
// If you use the maxFiles option, make sure you adjust it to the
// correct amount:
let fileCountOnServer = 2; // The number of files already uploaded
myDropzone.options.maxFiles = myDropzone.options.maxFiles - fileCountOnServer;
}
};
Originally I was doing something along these lines to programmatically upload a pre-existing file to Dropzone:
headerDropzone.emit("addedfile", imageFile);
headerDropzone.emit("thumbnail", imageFile, imageUrl);
headerDropzone.files.push(file);
However, referencing this Dropzone Github Issue I found an easier way to directly upload:
headerDropzone.uploadFiles([imageFile])
Unfortunately there are no references to this uploadFiles method in the Dropzone Documentation, so I figured I'd share some knowledge with all you Dropzone users.
Hope this helps someone
I had the same problem and found Dropzone's handleFiles(files) method.
So if you have inputTypeFileRef, you can
// inputTypeFiles.files is an object of type FileList
var fileArray = Object.values(inputTypeFiles.files || {});
myDropZone.handleFiles(fileArray);
That will also trigger all the Dropzone's events and pass file(s) data that it normally would by dragging a file on it - progress, file size, etc.
Hope it helped.
The latest Dropzone is lack of examples and the documentation is not clear or incomplete. You can use the following to add existing images to Dropzone.
for (var i = 0; i < imagesList.length; i++) {
let name = imagesList[i];
name = name.substring(name.lastIndexOf('/') + 1);
fetch(imagesList[i])
.then(res => res.blob())
.then(blob => {
let file = new File([blob], name, blob);
myDropzone1.addFile(file);
});
}
imagesList is a list of images which you want to add to Dropzone.
However, I am still facing a problem: Images are not being added or shown in the order/sequence as in imagesList. They appear rather random. Is there a way to make the images shown in the order/sequence as in imagesList?
Many of these answers are pretty dated, this is working for me in the latest Dropzone JS at the time of writing (take note of the included comments):
init: function() {
var dzObj = this;
// In my template I looped through existing files from the database and created:
// <div class="existing-image" data-url="/path/to/file.jpg"></div>
$('.existing-image').each(function() {
// I didn't have this data - works fine without
var mockFile = { name: '', size: '', dataURL: $(this).data('url') };
// Call the default addedfile event handler
dzObj.emit("addedfile", mockFile);
// The Dropzone JS FAQ incorrectly references "file" here instead of mockFile".
// The other parameters are outdated, dataURL goes in the object above,
// and you need to pass through other parameters.
// It DOES NOT WORK without the thumbnail event being triggered.
dzObj.createThumbnailFromUrl(mockFile, dzObj.options.thumbnailWidth, dzObj.options.thumbnailHeight, dzObj.options.thumbnailMethod, true, function (dataUrl) {
dzObj.emit("thumbnail", mockFile, dataUrl);
});
// Make sure that there is no progress bar, etc...
dzObj.emit("complete", mockFile);
dzObj.options.maxFiles = dzObj.options.maxFiles - 1;
});
}
#tjbp's response worked well for me, with the following changes:
I could not delete the programatically added file and then add another. I fixed this by removing this line, which was setting "maxFiles" to 0.
// If you use the maxFiles option, make sure you adjust it to the
// correct amount:
var existingFileCount = 1; // The number of files already uploaded
myDropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
To make sure the "Delete" button was visible, I had to add the following line:
if (mockFile.previewElement) {
mockFile.previewElement.classList.add("dz-success");
}
Nothing here worked for me with version 5.7.0 but this did:
var myDropzone = new Dropzone(document.body, {
url: "<?= site_url('site/upload') ?>",
acceptedFiles: "<?= $uploadFieldAcceptValue ?>",
maxFilesize: 15,
maxFiles: 5,
autoQueue: false,
thumbnailWidth: 80,
thumbnailHeight: 80,
init: function(){
var that = this;
that.on("addedfile", function(file) {
// remove the start button
var startButton = file.previewElement.querySelector(".start");
if(startButton){
startButton.parentNode.removeChild(startButton);
}
});
<?php if(is_array($userUploads) && count($userUploads) > 0) { ?>
<?php foreach($userUploads as $userUpload) { ?>
<?php $file = $userUpload['file']; ?>
var mockFile = {
name: '<?= basename($file) ?>',
size: <?= filesize($file) ?>
};
var fileUrl = '<?= base_url() . str_replace('\\', '/', preg_replace('~^'. preg_quote(FCPATH) .'~', '', $file)) ?>';
var callback = null;
var crossOrigin = null;
var resizeThumbnail = true;
that.displayExistingFile(mockFile, fileUrl, callback, crossOrigin, resizeThumbnail);
that.emit("success", mockFile);
that.emit('complete', mockFile);
<?php } ?>
that.options.maxFiles = that.options.maxFiles - <?= count($userUploads) ?>;
<?php } ?>
}
});
On Dropzone 5.7.0 there is a "displayExistingFile" function. I called it on init section, works fine.
/**
* Called when dropzone initialized
* You can add event listeners here
*/
init: function init() {
var mockFile = { name: "Filename 1.pdf", size: 12345678 };
this.displayExistingFile(mockFile, "../../assets/site/wp-content/uploads/cropped-ic_credifisco-1-192x192.png");
},

how to set text in ckeditor

How do I set text in CKEditor? CKEditor also needs to integrate with ckfinder.
I tried doing
// I need to set ckeditor text with a value in code behind. To get that value from code bhind, I am using a div which would be set in code behind. This is not hidden currently but I would do that eventually. I need to set this value to my ckeditor.
<textarea id="editor1" name="editor1"></textarea>
<script type="text/javascript">
window.onload = function () {
var edt = CKEDITOR.replace('editor1', { toolbar: 'Basic' });
CKFinder.setupCKEditor(edt, '/ckfinder/');
var t = <%=editortext.InnerText %>;
CKEDITOR.instances.editor1.setData(t);
}
If I put some static text for t, var t = "Some Text";
and then set
CKEDITOR.instances.editor1.setData(t); it works fine.
If I use,
var t = <%=editortext.InnerText %>;
CKEDITOR.instances.editor1.setData(t);
ckeditor is no longer displayed. Only text area is displayed. How to set text in ckeditor ? Please help
This syntax may be useful here:
CKEDITOR.instances['editor1'].setData(t); // where editor1 is id
OR try this
edt.setData(t);
<script>
function SetContents(value ) {
var oEditor = CKEDITOR.instances.MainContent_editor1;
var t = document.getElementById('<%=editor1.ClientID %>').value ;
oEditor.setData(t);
}
</script>
<script type="text/javascript">
var ckEditor = CKEDITOR.replace('<%=editor1.ClientID %>', {
// extraPlugins: 'bbcode',
// fullPage : true,
extraPlugins: 'docprops',
removeDialogTabs: 'image:advanced',
filebrowserImageUploadUrl: 'Upload.ashx',
resize_enabled: false,
toolbar: [
['Source', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
['FontSize', 'TextColor', 'BGColor'],
['Image']
]
});
var oEditor = CKEDITOR.instances.MainContent_editor1;
var t = document.getElementById('<%=editor1.ClientID %>').value;
oEditor.setData(t);
function pageLoad() { // this is because after postback jquery not working
var instance = CKEDITOR.instances['<%=editor1.ClientID %>'];
if (instance) {
CKEDITOR.remove(ckEditor);
}
CKEDITOR.replace('<%=editor1.ClientID %>', {
// extraPlugins: 'bbcode',
// fullPage : true,
extraPlugins: 'docprops',
removeDialogTabs: 'image:advanced',
filebrowserImageUploadUrl: 'Upload.ashx',
resize_enabled: false,
toolbar: [
['Source', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
['FontSize', 'TextColor', 'BGColor'],
['Image']
]
});
var oEditor = CKEDITOR.instances.MainContent_editor1;
var t = document.getElementById('<%=editor1.ClientID %>').value;
oEditor.setData(t);
}
</script>
Check in your browser's console for errors first. Also observe what is rendered from your backend code into this template. Most likely what you're missing are quotation marks "" and/or your rendered string contains unescaped apostrophes/quot. marks.
Console is everything.
this post is quote old but I hope I am not too late for others to see this:
You forgot to enclose the server side code with quotes:
var t = "<%=editortext.InnerText %>";
the page will be rendered like this:
var t = "your text here";
instead of
var t = your text here;
using your code will definitely break javascript's parser
You just put double quotes
for example :-
var mata = CKEDITOR.replace('meta_des');
var editor = CKEDITOR.replace('des1');
mata.setData("meta_des; ?>");
editor.setData("description1 ;?>");
here my meta_des is ckeditor and i want past my value in that ckeditor i will just put double quotes on my php tag and simply it will print my value that comes in database it will print.

Change content [] object property without removing or adding

I setup a list of objects, add them to content[] array list. So far so fine. Ember DOM in App.list show correct data. Now, when I start altering the content properties without remove/add/replaceAt() any object in App.list it seems Ember doesn't pick this up.
View:
{{#each item in App.list.content}}
{{item.title}}
{{/each}}
Code:
function myApp() {
App = Ember.Application.create({});
App.Item = Ember.Object.extend({
title: null,
parent: null
});
App.MyList = Ember.Object.extend({
title: null,
content: [],
changed: function() {
console.log('here');
}.observes('content')
});
App.list = App.MyList.create({
title: "foobar",
content: [
App.Item.create({
title: "item1"
}),
App.Item.create({
title: "item2"
})
]
});
console.log(App.list.content);
// Add 3rd object to list
App.list.get('content').pushObject(
App.Item.create({
title: "item3"
})
);
}
..and later in some random Ember ArrayController I do this:
for (var i = 0; i < 2; i++) {
App.list.content[i].title = "I CHANGED YOU";
}
Looking at my App.list the content is correct, but view is not. Am I missing something? If I have to guess ArrayHasChanged() seems to be rigged for array size changed or object being changed which I'm not doing, I'm altering property data within specific objects of the content[] array. Is it possible or do I have to removeAt()/Add/Delete objects?
You need you use get and set so the observers/bindings trigger with your changes.
// Bad
App.list.content[i].title = "blah";
// Good
App.get('list').objectAt(i).set('title', 'blah');
If this still does not work for you there might be something else missing. If you could post a jsfiddle that would help a lot!

how to remove form tools in ckeditor and also make size adjustable

I am using CKE Editor in my project. My requirement is to remove "FORM TOOLS" and make size of the CKE Editor ADJUSTABLE . So far I have displayed editor in web page successfully. I have searched google but unluckily i have got nothing. kindly help me on this.
just try this
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.removePlugins = 'forms';
};
Found one solution by reading documentation,
I added following configuration in config.js,
CKEDITOR.editorConfig = function( config )
{
// Define changes to default configuration here. For example:
CKEDITOR.config.resize_enabled = true;
CKEDITOR.config.width = 600;
CKEDITOR.config.autoGrow_minHeight = 600;
CKEDITOR.config.autoGrow_maxHeight = 600;
CKEDITOR.config.toolbar_Full =
[
['Source','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
// ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], // here i disable the form tools
'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['BidiLtr', 'BidiRtl' ],
['Link','Unlink','Anchor'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'],
'/',
['Styles','Format','Font','FontSize'],
['TextColor','BGColor'],
['Maximize', 'ShowBlocks','-','About']
];
};

Resources