Symfony 4 : WYSIWYG editors

The problem :

  • The majority of full free WYSIWYG editor bundles are not compatible with Symfony 4 ,Or at least until this moment ( April, 14th 2018 )

The solution :

let’s make it manually !!

1️⃣ Download CKeditor :

Is free . You can choose the suitable package according to your needs

2️⃣ Add the folder in /public/

Unzip the folder and put it under / public. 
/public/javascript is the best place. Reminder the path because you will need it in the next step.

3️⃣ Add the following script in your twig file :

{# templates/new_post.html.twig #}
{# Javascript Block #}
<script src="{{ asset('assets/javascript/ckeditor/adapters/jquery.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/javascript/ckeditor/ckeditor.js') }}" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('textarea.ckeditor').ckeditor();
});
</script>

4️⃣ Customize your form :

// src/Form/PostType.php

$builder
(-) ->add('content', TextareaType::class )
(+) ->add('content', TextareaType::class, array('attr' => array('class' => 'ckeditor')))

5️⃣ Transform the html content to text :

{# templates/post_show.html.twig #}
#before
{{ post.content }}
#after
{{ post.content |raw }}

🍰 🍬 Bonus :

If your are using Sonata Admin , you are almost need the following part to make sonata admin support your new awsome editor .

First , redo 1️⃣ 2️⃣ 4️⃣ and 5️⃣

3️⃣ Override Sonata Admin edit template :

{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}

{% block javascripts %}

<script src="{{ asset('js/ckeditor/adapter/jquery.js') }}" type="text/javascript"></script>
<script src="{{ asset('js/ckeditor/ckeditor.js') }}" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('textarea.ckeditor').ckeditor();
});
</script>
{{ parent() }}
{% endblock %}

6️⃣ Edit the configuration of Sonata Admin:

#sonata_admin.yaml
sonata_admin:
template:
edit: edit.html.twig

Enjoy 😄 !!


I’m Mouna , developer from Tunisia 
Feel free to put comments , questions or suggestions below ❤

References :