Advertising sustains the DA. Ads are hidden for members. Join today

On this page

Filter API overview

Last updated on
25 August 2023

The Filter API is conceptually the same in Drupal 8 as it was in Drupal 7 and before. The major changes are:

  1. New filters can be defined using plugins instead of hooks.
  2. Filters now need to specify a filter type if they want to work well with in-place editing.

API features

Text format config entities
\Drupal\filter\Entity\FilterFormat config entity: configure text formats, one text format can have one text editor.
Every text format consists of an ordered list of filters (filter plugins), with settings for those filters that do have settings. When filtering text, these filters are invoked in order.
Filter plugins
\Drupal\filter\Plugin\FilterInterface: filter plugins, to provide additional filters that are available to site builders to be used.
  • Plugin implementations must be annotated with the @Filter annotation so they can be discovered.
  • Discovered plugins' annotation metadata can be altered using hook_filter_info_alter()
  • \Drupal\filter\Plugin\FilterBase provides a default implementation so filter plugins don't need to implement every method
  • Every filter plugin must specify a filter type in its annotation. Filter types were added specifically to support in-place editing. There are four filter types:
    1. FilterInterface::TYPE_MARKUP_LANGUAGENon-HTML markup language filters that generate HTML. The filter converts something that's not HTML to HTML in a way that is not compatible with WYSIWYG editing.
    2. FilterInterface::TYPE_HTML_RESTRICTORHTML tag and attribute restricting filters to prevent XSS attacks. The filter restricts the HTML allowed, for example, to protect against XSS.
    3. FilterInterface::TYPE_TRANSFORM_REVERSIBLEReversible transformation filters. The filter performs a transform for which a WYSIWYG plugin exists to perform the same transformation (and its reverse) client-side. For example, <img data-caption="Druplicon"> may be (reversibly!) transformed to <figure><img><figcaption>Druplicon</figcaption></figure>.
    4. FilterInterface::TYPE_TRANSFORM_IRREVERSIBLEIrreversible transformation filters. The filter performs a transform for which a WYSIWYG plugin does not exist to perform the transformation client-side (especially, the reverse of it); instead, the WYSIWYG editor displays the unfiltered text. For example, Token Filter.
check_markup()
Using the check_markup() function, you can filter a user-supplied string using a text format. The return value has the type MarkupInterface and is fully filtered against the configured format.

See also

Help improve this page

Page status: No known problems

You can: