Add a custom button with mceToggleFormat to html editor

Silverstripe Version: 4.10


I’m trying to add a custom button to the TinyMCE editor in Silverstripe.

The button should use mceToggleFormat to let the CMS user to set/unset a span on the selected text.

I have this working perfectly in a non-silverstripe context here:

However, I’m stumped when it comes to translating this to Silverstripe. I’m a frontend developer and my php skills are very limited…

Could someone show me please how to get my linked code working in Silverstripe? :pray:

The current code in _config.php is:

$richText = clone TinyMCEConfig::get('cwp');
$richText->enablePlugins(['hr', 'charmap']);
$richText->insertButtonsAfter('removeformat', ['hr', 'charmap']);
$richText->removeButtons('indent', 'outdent', 'underline', 'copy', 'paste', 'pastetext');
TinyMCEConfig::set_config('richText', $richText);


TinyMCEConfig::set_config('richText', $richText);

This will set up a new configuration, which you’ll need to explicitly declare that you’re using wherever you want it in your HTMLEditorField instances.
If you want this to apply automatically to all new HTMLEditorField instances, you’ll instead want to remove this line, and remove the clone from that first line. That way you’re modifying the default config instead.

Note also that the cwp config is only available if you have cwp/cwp installed - if you don’t have that module installed you should use cms instead.

Aside from that, it looks like you’re declaring a new plugin. You’ll want that to be in its own .js file, and then you can tell tinymce where to find it with $richText->enablePlugins(['langmi' => '/path/to/plugin.js']);
You might find it easier to use the module loader to get the path, e.g:

use SilverStripe\Core\Manifest\ModuleLoader;

$module = ModuleLoader::inst()->getManifest()->getModule('silverstripe/admin');
$richText = TinyMCEConfig::get('cwp');
$richText->enablePlugins(['langMi' => $module->getResource('client/dist/js/my-plugin.js')]);
$richtext->insertButtonsAfter('redo', ['|', 'langMi']);