+31 20 - 261 14 99

Mr Treublaan 1-3
1097 DP Amsterdam
The Netherlands

A rich text editor in a custom Drupal form, example code including data sanitization for security

10 May, 2021 Drupal

Home Blog A rich text editor in a c...

Drupal rich text editor custom

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.

The form also uses Dependency Injection for a Form to implement a custom Drupal Service.

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

  1. Get the body via $form_state->getValue('body')['value'];. The ['value'] part took a bit of research.
  2. 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.
  3. / 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.

Wrap up

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.

Written by Joris Snoek | May 10, 2021

Join the conversation

Got some more time?

Related content
07 Jun, 2021 Drupal

Programmatically in multiple Views

02 Jun, 2021 Drupal

25 May, 2021 Drupal

With new features like: @-mentions, drag-and-drop images & general settings.

Let's Talk

Pease tell me all about your project.
+31 (0)20 - 261 14 99  /  joris@lucius.digital.