Jan's Development Microblog
Go back to blog overview
| Jan Valkenburg | PHP | Reading time: 10 min

How to add SunEditor to your website

When I built the first version of this micro-blogging platform I left out a few major parts. A few weeks back I decided, it was time to include a WYSIWYG editor

Why did I leave out some parts of the project?

The reason I left out parts of the platform was to be able to set up a website within 2 weeks from scratch. The goal was to launch a minimal useable product and include the missing parts later on when the blog grows or when I have some inspiration. The thing is you can spend hundreds of hours building a platform and never be able to launch it because it is not finished. This would be a waste of time and effort. The alternative is to build a minimal product and extend it with time. This way you can see what is required for the product instead of guessing what would be necessary. The last one is always a bit dangerous as you often make mistakes or misjudge the needs of a product or platform. Why would you implement a newsletter into your platform if you only have five subscribers? This would be a waste of time. It would be another story when you have 500 subscribers.

The same goes for the text editors within the website to write the articles. As I am the only one writing those blogs there was no need to include a WYSIWYG editor on the website. Sometimes the HTML code would become somewhat unreadable, but it was doable. Also not using a WYSIWYG editor gives you full control. So the author can decide on how to show the content to the reader. This can be especially handy for code snippets. The downside is that if you want to include an image you've to upload it on the webserver directly and link to it. This required you to have a second program needed to write the article on the website. 

Why did I choose SunEditor?

Through the years I have used multiple WYSIWYG editors. The most famous ones are TinyMCE and CKEditor. In the past, I would opted for one of those, but they went the commercial way by asking for money or the need to have an account. So that would be a big no. So in the last few months, I looked around on the internet for alternatives. There were a few but those didn't meet my requirements. After a tip from my colleague at work, I decided to try out SunEditor. While not working as expected I did include it in my microblogging platform. For now, it's just for personal usage so the stakes are low.

How do I load SunEditor into my website?

To include the WYSIWYG SunEditor into your website we need the basic setup as shown below.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/suneditor@latest/dist/css/suneditor.min.css">
<script src="https://cdn.jsdelivr.net/npm/suneditor@latest/dist/suneditor.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/suneditor@latest/src/lang/en.js"></script>

<form method="post" id="form">
    <label for="form_content">Content</label>
    <textarea id="form_content"></textarea>
<form>

<script>
    SUNEDITOR.create(document.getElementById('form_content'));
</script>

After refreshing the page in the browser it should look like the screenshot here below.

Setting up the toolbar

From this point on we need to change the toolbar to our needs. For today's website, we have to enable the following options: bold, Text formats (h2, h3, etc). listings, Links, images, video, code preview. A full list of the toolbar options and more can be found on this SunEditor option page.

For my own needs, I ended up with the setup below:

<script>
const editor = SUNEDITOR.create(document.getElementById('form_content'), {
buttonList: [
['formatBlock', 'blockquote', 'bold', 'list', 'removeFormat'],
['link', 'image', 'imageGallery', 'video', 'audio'],
['codeView'],
],
formats: ['h2', 'h3', 'p', 'pre'],
stickyToolbar: false,
height: '60vh',
imageUploadUrl: 'suneditor/file_upload.php',
imageGalleryUrl: 'suneditor/media_gallery.php',
});
</script>

How to submit the form?

While testing it I was unable to save the text to the server. The content was not included in the POST request to the server for some reason. Why this happens I am not sure, but I remember that this was a thing for all WYSIWYG editors. However, after some help from ChatGPT and Google, I found a solution for this issue. I had to include an event listener that detects when the form is submitted and moves the content from the editor into the textarea. Now the content is submitted to the server without any problems. 

<script>
document.getElementById('form').addEventListener('submit', function (event) {
event.preventDefault();
document.getElementById('form_content').value = editor.getContents();
this.submit();
});
</script>

Uploading images to the server

A blog without images is no blog at all. So it is time to include some code to upload images to the server. For this project, I had to use some PHP code. Before writing it myself I checked the internet to see if there was some prefab code as the documentation was not useable at all, but I couldn't find any. So in the end I wrote the method here below. I might clean it up a bit in the future.

file_upload.php:

$success = false;
$allowed_extensions = array("jpg", "jpeg", "png", "gif");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_FILES["file-0"]) && $_FILES["file-0"]["error"] == 0) {
$extension = pathinfo($_FILES["file-0"]["name"], PATHINFO_EXTENSION);
if (in_array($extension, $allowed_extensions)) {
$file_name = uniqid() .".".$extension;
$upload_path = __DIR__."/../../assets/img/".$file_name;
$filesize = filesize($_FILES["file-0"]["tmp_name"]);
if (move_uploaded_file($_FILES["file-0"]["tmp_name"], $upload_path)) {
$success = true;
}
}
}
}

if ($success) {
$data = [];
$data['result'] = [
'url' => '/assets/img/'.$file_name,
'name' => $file_name,
"size" => $filesize
];
} else {
$data = [];
$data['errorMessage'] = 400;
$data['result'] = [];
}

header('Content-Type: application/json');
echo json_encode($data);

Linking the Image Gallery

The last part to set up was the image gallery. The media gallery used in SunEditor seems to be very basic. It can only be used to display and select images. There is no option to use folders or to delete images. I really hope I'm missing something here. Let me know if there is an easy way to include this in SunEditor. The PHP script I wrote to show the images in the Gallery can be found below. 

media_gallery.php:

$files = glob(__DIR__ . "/../../assets/img/*.{jpg,png,gif}", GLOB_BRACE);

$media = [];
foreach ($files as $file) {
$media[] = array(
'name' => basename($file),
'src' => '/assets/img/' . basename($file)
);
}

$data = [];
$data['statusCode'] = 200;
$data['result'] = $media;

header('Content-Type: application/json');
echo json_encode($data);

After applying some missing styling it looks like this. Very basic but it works.

The final stretch

You would think we are finished with the configuration and setup of the WYSIWYG SunEditor, but that would be far from the truth. There was still a lot of fine-tuning; some parts of the editor were wrongly aligned and others were not working. The toolbar would just disappear when it got out of the viewport, the sticky option was not working at all. So I had to set a height of 60vh to the textarea and disable the sticky toolbar completely. All the modals were not aligned with the editor itself. At some point, I thought everything was good enough and uploaded the code to the live website. The whole thing came down. The main issue I had was that it didn't support HTML code examples at all in the WYSIWYG SunEditor. So I had to disable the editor as soon as possible and went back to figure out how I should fix this one. Code examples are one of the most important functions within my development blog. So after a few days of thinking I opted for just not using < and > but replacing them with < and >. While it is not perfect it works. And even now I still have issues with it as I am losing content due to the editor. I hope it will be ironed out in the upcoming time.

6621895c37804.png

Final word

Another part of my own micro-blogging platform is done. While it was a lot of work to add the WYSIWYG SunEditor it seems to be working. It is not perfect and I have to watch out I don't lose any content due to issues with the editor. I hope that this text editor will improve in the future. At the moment they are still working on it, so that is a good thing. 

In case one of you wants to include this editor in your website I hope you can use my code examples and experience. For normal use, it should be fine. Please let me know if this one was helpful. Or if you have any questions just send me an email.