Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughA rich text editor in a custom Drupal form, example code including data sanitization for security
(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
- Get the body via
$form_state->getValue('body')['value'];
. The['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.
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.
About Drupal Sun
Drupal Sun is an Evolving Web project. It allows you to:
- Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
- Facet based on tags, author, or feed
- Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
- View the entire article text inline, or in the context of the site where it was created
See the blog post at Evolving Web