May 17, 2019 in Drupal 8, Snippets

When editing notes, an often mentioned problem of webmasters is the lack of preview of their text. With this snipped you can embed the css of your theme in CKEditor, which makes it much more visible towards your webmasters.

use Drupal\editor\Entity\Editor;

/**
 * Implements hook_ckeditor_css_alter().
 *
 * Injects our CSS sheets anytime CKEditor has loaded.
 *
 * @param array $css
 * @param Drupal\editor\Entity\Editor $editor
 */
function MYMODULE_ckeditor_css_alter(array &$css, Editor $editor) {
  if (!$editor->hasAssociatedFilterFormat()) {
    return;
  }

  $known_formats = [
    'filtered_html',
    'full_html',
  ];

  if (in_array($editor->getFilterFormat()->id(), $known_formats)) {
    $css[] = drupal_get_path('theme', 'MYTHEME') . '/css/MYCSSFILE.css';
  }
}