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

Aug 25, 2020

(Available as freelancer)
Joris Snoek
Business Consultant
/ Drupal Developer

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.

Comments

Need even
more knowlegde?