Setting custom settings for a property through code in EPiServer CMS R2 Beta
Dec 20, 2010
Previously I blogged about New property types in EPiServer CMS R2 Beta. It led to a little discussion in the comments. Specifically Erik Nordin asked if it was possible to set the custom settings through code.
Well after a little quality time with reflector I’ve found out how. On publishing a page the code will look for a “Select list (multiple selection)” control called ChildPages. If one is found then it sets the list of available options to the child pages of the current page (value is the page ID and text is the page name). This could be useful in scenarios where editors need to feature a page but we want to give them something simple and/or controlled to work with.
//Hook up Instance_PublishingPage however you like
void Instance_PublishingPage(object sender, PageEventArgs e)
{
string childPagesPropName = "ChildPages";
//Look for a property called "ChildPages"
if (e.Page.Property[childPagesPropName] != null && e.Page.Property[childPagesPropName].GetType() == typeof(EPiServer.SpecializedProperties.PropertyCheckBoxList))
{
//Get the MultipleOptionsListSettings for the PropertyCheckBoxList
PropertyCheckBoxList listProp = (PropertyCheckBoxList)e.Page.Property[childPagesPropName];
//Get the property respository and save
IPropertySettingsRepository propRepository = new PropertySettingsRepository();
PropertySettingsContainer container;
if (propRepository.TryGetContainer(listProp.SettingsID, out container))
{
PropertySettingsWrapper wrapper = new PropertySettingsWrapper();
foreach (PropertySettingsWrapper wrap in container.Settings.Values)
{
if (wrap.PropertySettings.GetType() == typeof(MultipleOptionsListSettings))
{
wrapper = wrap;
break;
}
}
if (wrapper != null)
{
//Update the settings to include all child pages
MultipleOptionsListSettings settings = ((MultipleOptionsListSettings)wrapper.PropertySettings);
//Populate the property with all child pages (if any exist)
var childPages = DataFactory.Instance.GetChildren(e.Page.PageLink);
settings.ListOptions.Clear();
foreach (PageData page in childPages)
{
settings.ListOptions.Add(page.PageName, page.PageLink.ID.ToString());
}
wrapper.IsGlobal = false;
//Save the settings back to the repository.
propRepository.Save(container);
}
}
}
}
Obviously this is a very quick demo but I am sure this can be expanded out for several uses.
This code was written in EPiServer CMS 6 R2 beta but approach should work on EPiServer CMS 6.
Disclaimer
This hasn’t been anywhere near a production box and has been tested for all of 30 seconds. Also it is running on the current beta so use at your risk.