Optimize the Rich Text Editor in Sitecore

When it comes to building a Sitecore site your first thought probably isn’t that you are going to need to make any setting updates or customization’s to the rich text editor. After all when you learn about building a site its mostly focused around creating components to add and remove from pages, but there are a couple of things that will greatly enhance your content editors experience.

Configure the toolbars

Out the box Sitecore ships with 4 toolbar configurations. These are defined in the core db here:

  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Default
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Full
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text IDE
  • /sitecore/system/Settings/Html Editor Profiles/Rich Text Medium

The “Rich Text Default” toolbar

Default Toolbar

The “Rich Text Full” toolbar

Full Toolbar

The “Rich Text IDE” toolbar

IDE Toolbar

The “Rich Text Medium” toolbar

Medium Toolbar

As the name suggests, by default your content editors will see the default toolbar that contains a very limited number of options. This may in-fact be to limited and you need to offer the content editors one of the toolbar’s with more options. Equally, the full toolbar may give to many options such as font’s and you would want to offer a more restricted set of options.

Setting a toolbar on a field

You can set a toolbar on each individual field by specifying the path in the template fields source field. This is particularly useful when a field needs specific options, such as a text area that should allow a user to configure bold, italics and links but shouldn’t ever contain an image.

Setting toolbar in on an individual field

Updating the default toolbar for a rich text field

When you want to change the toolbar for all rich text fields, a better option is to update which toolbar is used by default. You can do this with a patch config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
      <setting name="HtmlEditor.DefaultProfile" value="/sitecore/system/Settings/Html Editor Profiles/Rich Text Full" />

Updating the rich text editor css

A second way of customizing the rich text editor that you should consider is to make changes to the css file that the editor uses. By default this will use a css file called default.css that you will find in the root of the site. You can see this being referenced form a config setting if you look at the showconfig.aspx page.

    CSS file for HTML content of Sitecore database.
    The file pointed to by WebStylesheet setting is automatically included in Html and Rich Text fields.
    By using it, you can make the content of HTML fields look the same as the actual Web Site
<setting name="WebStylesheet" value="/default.css" />

You can change this to use a different css file using a patch config file as follows:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
      <setting name="WebStylesheet">
        <patch:attribute name="value">/rich-text-editor.css</patch:attribute>

Now you may be wondering why you would want to do this, after all Sitecore offers an experience editor mode that will show the entire webpage as it will appear to visitors and also offers inline editing. However some aspects of a page can be better achieved using css styles rather than new components or new fields and content editor will need both an easy was to apply these style and a visual way to see that they have been applied, irrespective of if they are using the experience editor or the content editor.

For example, in this section of a blog post from Scott Hanselman he has highlighted some text as an aside which can easily be achieved in a rich text editor by applying a css class.

Hanselman Blog Aside

The first step to enabling this in Sitecore is to make sure you’re using a toolbar that allows the user to select css classes (that’s any but the default).

Next by creating a stylesheet that just contains the relevant style to be applied, the content editor can now select this in the css drop down;

.aside {
    border-left: 2px solid #e2842c;
    background-color: #f7f7f7;
    padding: 5px;
    margin: 5px;
    display: block;

CSS drop down

The preview will now also give visual feedback indicating what this is going to look like. It doesn’t have to look exactly like the webpage will, just enough for the content editor to understand.

Rich Text Editor


Sitecore Rendering Datasource Restrictions

Datasources on Sitecore Renderings are the basis for content authors to combine a variety of components to form a page, without the need for all the fields to exist in the context item. They also form the underpinnings of switching out content based on personalization rules.

To make life easier for content authors there are two properties which should always be set; Datasource Template and Datasource Location.

Datasource Template

The datasource template field is fairly straightforward to understand. It specifies what type of template is compatible with a rendering.

If the content editor try’s to select an incorrect template they will see an error message like this and the ok button will be disabled:

Incorrect template type

The template reference can point to either the final template that an instance of which will be created, or a template that had been inherited. So if you structure your templates using base template like I describe in my article on How I structure Sitecore Templates then you can reference the base template and anything including it will become available.

However there is a fundamental flaw in linking to a base template. As well as restricting the template that can be selected, specifying the template type also enables the ability to create new content, which will create it as the form of the template specified. So only link to the templates you want your editors to create.

Datasource Location

The datasource location property (as the name suggest) enables you to restrict where in the content tree items can be selected from (or new content created).

Simply specify the folder the content should be placed in and the rest of the content tree will now be hidden from content authors.

Datasource Location Fixed Path

Multi-site solutions

If your solution contains more than one website this may cause a problem as you likely want to be able to restrict certain content to certain sites and may additionally have a global content folder.

Datasource Location Multiple Folders

The first solution to this is to add multiple path’s separated by a pipe.

Datasource Location Multiple Folders Config

This will enable multiple folders to be shown to the user, but it wont enable any sort of restriction.

The second option is to add an xpath query find the relevant folder. This can also be used in conjunction with the static path by being pipe separated as in the last example.

A query like this:

Datasource Location XPath

/sitecore/content/Shared Components/Shared Hero Banners|query:./ancestor-or-self::*[@@templatename='Site']/Components/*[@@templatename='Hero Banners']

Will produce the desired output like this:

Datasource Location XPath Result

Here you can see the shared hero banners folder is available as is the specific hero banner folder for the current site, but not the hero banner folder from the other site.

Using template source restrictions in Sitecore

The source field on a template definition is a great and easy way to enhance your content editors experience.

With fields types such as a tree list, this can be used to restrict the content tree to the section that is relevant. e.g.

Adding a source property like this:

Source Restriction

Will change how a tree list displays from this:

Unrestricted Tree List

To this:

Restricted Tree List

Multi-Site Solutions

The source field however is far more powerful than just pasting in a fixed path to an item. Rather than a static path you can use xpath to make the results based on a query, such as restricting options on a droplink by template type.

In a multi-site solution this is particularly useful, by restricting the options to the site that your content item is on.

With a fixed path the best we could do in the above example would be to set the restriction to the nearest folder that could access both, resulting in a restriction like this:

Fixed restriction showing both sites

While this makes some improvement for the user, but not hugely and they can still select content from the wrong site.

By using an xpath query that utilizes the ancestor-or-self function with a template name, the restriction will dynamically be based on navigating up the content tree from the current item until the template is found and then showing items from it or in this example going back down to the home item.


Resulting in an output like the original example, but dynamically changing to be the correct items for where the current content item is located:

Treelist with dynamic restriction

Creating a WFFM Save action with Field Mappings

The Sitecore Web Form for Marketers module offers content editors a flexible way to create data capture forms and then trigger certain actions to occur on submission. There’s a whole host of save action options out the box, such as sending an email, enrolling the user in an engagement plan or updating some user details.

However one save action that is often required is the ability to send the data onto a CRM system so that it can get to the people that need to act on it, rather than staying in Sitecore with the content editors. To do this your best option is to create a custom save action that can send on the information.

Creating a Save Action in Sitecore

Save actions in Sitecore are configured under /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Save Actions. Here you can see all the standard ones that come out the box and add your own.

Right click Save Actions and insert a new Save Action. You will need to fill out the Assembly and Class fields so that Sitecore knows which bit of code to execute (details on creating this bit below).

Custom Save Action Sitecore Item

Adding Field Mappings

To really make your save action usable you will want to allow the content editor to map the fields on their form with the ones in the CRM, rather than relying on them both having the same name and hard coding the expected WFFM field names in your save action logic.

On your Save Action Item in Sitecore their are 2 fields to fill out to enable the editor in WFFM (Editor and QueryString). Luckily Sitecore provide a mapping editor out the box so there’s very little effort involved here.

Within the Editor filed add the value:


And within the querystring field, add your list of fields in the format fields=FieldName|FieldDisplayText

fields=FirstName|First Name,LastName|Last Name,EmailAddress|Email Address,CompanyName|Company Name


Custom Save Action Field Mappings

When the content editor now adds the save action to their form they will now be able to select a form field for each of these fields.

Custom Save Action Select Fields

Creating the Save Action in code

To create the save action you will need a class that inherits from either ISaveAction or WffmSaveAction. I’ve used WffmSaveAction as it already has some of the interface implemented for you.

The field list you added to the Querystring property of the save action in Sitecore will need to be added as public properties to your class. Sitecore will then populate each of these with the ID the field gets mapped to or null if it has no mapping.

Then all that’s left is to add an Execute method to populate your CRM’s model with the data coming in through the adaptedFields parameter and send it onto your CRM.

using Sitecore.Data;
using Sitecore.WFFM.Abstractions.Actions;
using Sitecore.WFFM.Actions.Base;
using System;

namespace MyProject.Forms
    public class SendFormToCrmSaveAction : WffmSaveAction
        public string EmailAddress { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string CompanyName { get; set; }

        public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data)
            // Map values from adapted fields into enquiry model
            IEnquiry enquiry = new Enquiry();

            enquiry.Email = GetValue(this.EmailAddress, adaptedFields);
            enquiry.FirstName = GetValue(this.FirstName, adaptedFields);
            enquiry.LastName = GetValue(this.LastName, adaptedFields);
            enquiry.CompanyName = GetValue(this.CompanyName, adaptedFields);

            // Add logic to send data for CRM here

        /// <summary>
        /// Get Value from field list data for a given form field id, or return null if not found
        /// </summary>

        /// <param name="formFieldId"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        private string GetValue(string formFieldId, AdaptedResultList fields)
            if (string.IsNullOrWhiteSpace(formFieldId))
                return null;
            if (fields == null || fields.GetEntryByID(formFieldId) == null)
                return null;
                return fields.GetValueByFieldID(formFieldId);

How I structure Sitecore Templates

Templates are the building blocks for a Sitecore installation, they’re amazingly flexible and with capabilities such as inheritance you can produce an elegant architecture, or alternatively a complete mess. Here’s how I like to structure things:

Base Templates

BaseTemplatesFirst off I have a folder of base templates. These are the building blocks for all the fields that will end up in a component data source or an actual page via inheritance. By setting them up as a base template we can re-use the same field definition for things like headings, but more importantly it keeps them focused on a specific purpose rather including details of the entire eventual item.

One additional rule I have for base templates is that they should only contain one data section within them. This in turn helps keep them focused on a specific purpose.

Page Templates

PageTemplatesNext we have pages. You guessed it, a page template is what a content editor will create an instance of when they make a page. It’s responsibility is to bring together default presentation details, the set of fields on the page and insert options for the pages beneath it.

All fields are inherited from base templates and standard values are used to define the defaults for the page.

Additionally to make the CMS experience as easy as possible for the content editors an icon should be set so that a page type can be visually identifiable.

Component Templates

ComponentTemplatesA component template is the equivalent of a page template but for data sources.

Like page templates all the fields are inherited from base templates and standard values are used to define the defaults for the page. An icon should also be set to make content types easily identifiable by content editors.

Folder Templates

FolderTemplatesFolder templates are often overlooked but they are an essential part of creating a decent user experience.

Folder templates are created to define the insert options for components and site settings rather than having them set on the site content tree.

Where relevant a folder template should also include itself as one of the insert options so that content editors can organise their content into sub-folders.

Parameter Templates

ParameterTemplatesWhen a component needs some config to customise its look and feel that is not content, it can be better to use Rendering Parameters rather than a data source.

Site Setting Templates

SettingsTemplateA Site configuration template is useful to contain various global settings for a site. This could include things such as the Site Logo, Google Analytics account details etc. Settings should be segmented into logical sections that have been defined in Base Templates and then inherited.

It can also be useful to separate some settings into their own template item depending on the scenario of what the setting is for.

Group Into Folders

With each these template types created, you’ll end up with a tree structure that looks something like this.


Data Source vs Rendering Parameters

Control Properties

On the face of it being able to specify Rendering Parameters, or a Data Source on a control achieves a very similar goal. You want to componentise your page and not fill up your page type item with fields for specific renderings. Everything should be isolated in it’s own little compartment.

Linking a rendering control to a Data Source does this by moving all your data to a completely separate item, that can be re-used over multiple pages and even swapped out to do personalization or A/B testing.

Equally, using Rendering Parameters does this just as well. Just like a Data Source, you can create a template for the fields that need to be entered, and the data is kept in the same place that a link to a Data Source would be specified.

But what should I use?

The easiest way I can describe it is by asking, are you storing content or something else?

If the answer is content then you most likely want a data source. Alternatively, if it’s something else like some config for a filter, or a background colour you will most likely want a rendering parameter (but there could be exceptions).

Data Sources

Data Sources have some distinct advantages over a Rendering Parameter including:

  • Data can be edited in the Experience Editor inline in your page
  • Language versions are very easy to understand by content editors
  • Easily used for personalization and testing
  • Can be reused on as many controls as you like

These things all make a Data Source a perfect option for anything content related. Without them you loose some big features related to content and ease of use. There are times non-content is also a good option. e.g. A hero banner on a page could be used across multiple pages and as well a reusing the text, if a background colour is also customizable you would want to be re-using that too.

Rendering Parameters

Likewise Rendering Parameters also have there benefits:

  • Doesn’t create an extra item to publish. You just have to publish the page your editing, not the related data source
  • Easy to access in the control properties of the item your looking at, without having to find the related data source

These features make Rendering Parameters ideal for the non-content config of a control and removes non-content fields from your item templates. The thing to be aware of though is you can’t easily do A/B testing or personalization with a rendering parameter, so while it’s nice for your items to only contain content, that might not be the only thing that’s being tested.

How about both?

There is also nothing to stop you using a Rendering Parameter and a Data Source at the same time.

You could have a situation when a Data Source is being used to populated the content on multiple different controls. Each control may have some additional config needed, such as text colour or text size. Keeping this data in the data source might become problematic as on one rendering your text may need to be black, whereas on another it may need to be white. By moving these fields to Rendering Parameters, you keep the benefit of a shared Data Source for content, while the Rendering Parameter takes care of the presentation config.

Sitecore html cache not clearing on publish

So you’ve got separate content management and content delivery servers, but when you publish the change is only visible on the content management box.

A likely cause is that you’ve enabled some caching but haven’t updated the config files to clear the cache on your content delivery server.

Sitecores config files contain a list of handlers for what should happen when the event publish:end and publish:end:remote are triggered. Publish end is for the content management server, whereas publish end remote is for your delivery servers. The handler we’re interested in is Sitecore.Publishing.HtmlCacheClearer which contains a list of sites to have the cache’s cleared on.

By default this will contain one entry for website, the default name given to your site in the sites config when you install sitecore. However you will have changed this if your solution supports multiple sites, or if you changed it as part of some future planning to support multiple sites. If your site is missing, just add it to the live (via a patch file of course)

<!-- Html Cache clear on publish events -->
<!-- Force FULL cache clear on publish-->
<event name="publish:end">
 <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache" patch:source="BaseSettings.config">
  <sites hint="list">
<!-- Html Cache clear on publish events -->
<!-- Force FULL cache clear on publish-->
<event name="publish:end:remote">
 <handler type="Sitecore.Publishing.HtmlCacheClearer, Sitecore.Kernel" method="ClearCache" patch:source="BaseSettings.config">
  <sites hint="list">

Note: in the sample above I have removed all other handlers to simplify the example. You should not remove these from your solution.

For more info on cache clearing and optimising it, see John Wests blog series on the subject here https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/sitecore-output-cache-clearing-optimization-1-8-introduction-john-west-sitecore-blog

Sitecore: Programmatically adding contacts to a list

From Sitecore 8 the EXM module now uses lists to manage mailing lists rather than roles against a user. The built in Subscription form control that comes with EXM has also been updated to add contacts to this list. However the subscription control remains WebForms only, so if you implementing an MVC solution you’re going to need to write your own. There’s also many other scenarios where you may want to programmatically create and add a contact to a list.

Under the hood, contact lists aren’t even a list at all. Rather they are actually just a Facet on the Contact record that contains the list id’s for all the lists the contact is a part of. You can see this by looking in the contacts collection in the analytics mongo db.

List Tag on Contact

Or in the Contacts table in the Reporting SQL db.

List Tag on Contact SQL

If you wanted to add a contact to a list you could in theory just add the relevant tag to the contact record like this:

public void AddContactToList(Contact contact, Item list)
   using (new SecurityDisabler())
      contact.Tags.Set("ContactLists", list.ID.ToString());

But I wouldn’t. The problem with this approach is your going to miss out any logic that will handle updating the counts of contacts in contact lists. Best to use one of the provided list api’s instead.

Adding a contact to a list

Sitecore has a ContactListManager object that has a method to associate contacts with lists. All you need to do is create an instance of it and pass it a list of contacts.

public void AddContactToList(ContactData contact, ContactList list)
    ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;

    List<ContactData> contactList = new List<ContactData>();

    listManager.AssociateContacts(list, contactList);

Removing  a contact from a list

Just like adding a contact, there’s also a handy method for removing one too.

public void RemoveContactFromList(ContactData contact, ContactList list)
    ContactListManager listManager = Sitecore.Configuration.Factory.CreateObject("contactListManager", false) as ContactListManager;

    List<ContactData> contactList = new List<ContactData>();

    listManager.RemoveContactAssociations(list, contactList);

What’s that ContactData object?

Chances are you don’t have a ContactData object (Sitecore.ListManagement.ContentSearch.Model.ContactData) and instead probably have a tracking contact (Sitecore.Analytics.Tracking.Contact). For the purposes of adding and removing a contact from a list, all your ContactData object really needs is its identifier, which you can do with the following:

public ContactData ConvertContactToContactData(Sitecore.Analytics.Tracking.Contact contact)
    return new ContactData()
        Identifier = contact.Identifiers.Identifier

Intro to Unicorn

Unicorn is a utility for Sitecore that solves the issue of moving templates, renderings, and other database items between Sitecore instances.

This video gives a great introduction to what it is and how it works. It’s for Unicorn 2 and Unicorn in now on version 3, but it’s still a good starting point.

More information on unicorn can be found at. https://github.com/kamsar/Unicorn

Sitecore: Sharing field data across languages

This is the third in a series of blog posts covering everything you should need to know for building a multilingual website in Sitecore.

Part 1 – Adding languages for a multilingual site
Part 2 – Translating text in your presentation

In the first two parts to this series I concentrated on how you can setup Sitecore to allow different language versions of content to be entered. In some instances though your content will contain fields which should remain the same across all language versions. This could be for product sku’s, dimensions of an object or possibly image fields.

To make a field share it’s values over multiple languages, in the template definition tick the shared checkbox against the field.


It’s worth noting though that as well as making the field value the same across all languages, it will also be shared between all versions within the language.

Although the interface gives the impression that a field can be the default (versioned), unversioned, shared or unversioned and shared. The value of the unversioned checkbox actually become meaningless once shared has been ticked and there really are only 3 options; Versioned, Unversioned and Shared.