2010-04-13

Adding buttons to the TinyMce editor in EPiServer 6 programmatically

While developing ImageVault we needed to add buttons to insert images in the TinyMce editor that ships with EPiServer CMS 6. The buttons are decorated with a TinyMCEPluginButtonAttribute and they can be added manually by entering admin mode and modifying the settings for the XHTML property (see Oskars post "Add functionality to the rich text editor in EPiServer cms 6").
To do this by code this was rather simple since EPiServer has a great Api (even that it could contain more examples)...

The settings are stored in the EPiServer database and is accessed using the PropertySettingsRepository class.
To get the current settings for the TinyMce editor, just create a repository and use the GetDefault method


PropertySettingsRepository p = new PropertySettingsRepository();
PropertySettingsWrapper defaultSettings = p.GetDefault(typeof(TinyMCESettings));

The PropertySettingsWrapper contains metadata for the settings, like DisplayName, Id etc.
It also contains the specific setting for the TinyMce editor in the property PropertySettings.

To create a new settings for the TinyMce editor with some buttons added we can use the code below.

PropertySettingsRepository p = new PropertySettingsRepository();
PropertySettingsWrapper defaultSettings = p.GetDefault(typeof(TinyMCESettings));

//create a copy of the default settings
PropertySettingsWrapper copy = defaultSettings.Copy();
copy.DisplayName+="(My copy)";
TinyMCESettings settings = copy.PropertySettings as TinyMCESettings;

//create a new toolbar row for my buttons
ToolbarRow row = new ToolbarRow();
settings.Toolbars.Add(row);

//the buttons are added using the name defined in the
//ButtonName property of the TinyMCEPluginButtonAttribute.
row.Buttons.Add("mybutton1");
row.Buttons.Add("separator");
row.Buttons.Add("mybutton2");

//Save the copy as a global setting
p.SaveGlobal(copy);

//Set it as default
p.SetDefault(copy.Id);

Quite easy. The separator button is included in EPiServer 6 the others need to be added using classes decorated with the TinyMCEPluginButtonAttribute.

Note!
To actually use this code in EPiServer you need to insert it somewhere :) The easiest way is to create a InitializationModule class (implement IInitializaionModule and mark it with the InitializationModuleAttribute). Then in the Initialize method, add your code to the InitializationEngine.InitComplete event.

public void Initialize(InitializationEngine context) {
context.InitComplete+=(sender,args)=> MyInstallButtonsMethod();
}

More about EPiServer Initialization on episerver world.