I needed to implement a rich text editor in a custom form (for the Drupal intranet distribution OpenLucius). I couldn't find a complete working solution right away, but I figured it out. So, for anybody who needs rich text editing: here is some example code.
See the Drupal form file that contains the code underneath. This it not an installable module, but a mockup file that lives in 'your_module/src/Form'. More info on building custom forms.
Explaining most important Drupal code
Make Rich text editor available for end-user
This is all you need to get the editor to work, assuming you're working in a (standard) Drupal install, that has the 'basic_html' filter defined. A Drupal Minimal install doesn't have this, but of course you can also configure your own Text Format and use that in this custom form.
Handle rich text in submit of custom Drupal form
- Get the body via
['value']part took a bit of research.
- For security reasons sanitize the data with help of
check_markup($body,'basic_html');. Drupal 9's filter.module still provides this function that you can use in this more procedural way.
- / 4. I mocked up the 'edit' mode. If you implement that, here is how you can switch between saving a new entity, or updating an existing one.
Ok, that's it for now. It's not that much, but hopefully valuable if you want to implement a rich text editor in your custom Drupal form.