Skip to content

Instantly share code, notes, and snippets.

@AThraen
Created December 30, 2022 12:45
Show Gist options
  • Select an option

  • Save AThraen/a5c08179a18a5ba1fc65b7228fa7051c to your computer and use it in GitHub Desktop.

Select an option

Save AThraen/a5c08179a18a5ba1fc65b7228fa7051c to your computer and use it in GitHub Desktop.
Content Creation rules for Optimizely CMS. Support rules defining where certain content types should be created. So you don't end up with a lot of banners in "for this page" folders.
using EPiServer.PlugIn;
using EPiServer.Shell.ObjectEditing;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// Rule that specifies where a certain type of content should be put on creation
/// </summary>
public class ContentCreationRule
{
[Display(Name = "Content Type", Order = 10)]
[SelectOne(SelectionFactoryType = typeof(ContentTypeSelectionFactory))]
public virtual string ContentTypeID { get; set; }
[Display(Name = "Destination", Order = 20)]
public virtual ContentReference ParentToMoveTo { get; set; }
}
[PropertyDefinitionTypePlugIn]
public class ContentCreationRuleList : PropertyList<ContentCreationRule> { }
[ModuleDependency(typeof(InitializationModule))]
public class ContentPlacerInit : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
var cevents = ServiceLocator.Current.GetInstance<IContentEvents>();
cevents.CreatingContent += Cevents_CreatingContent;
}
private void Cevents_CreatingContent(object sender, ContentEventArgs e)
{
var rules = ServiceLocator.Current.GetInstance<IContentLoader>().Get<StartPage>(ContentReference.StartPage).ContentCreationRules;
var rule=rules.FirstOrDefault(r => r.ContentTypeID == e.Content.ContentTypeID.ToString());
if (rule != null)
{
if (!e.Content.ParentLink.CompareToIgnoreWorkID(rule.ParentToMoveTo))
{
e.Content.ParentLink = rule.ParentToMoveTo;
}
}
}
public void Uninitialize(InitializationEngine context)
{
}
}
using EPiServer.Shell.ObjectEditing;
public class ContentTypeSelectionFactory : ISelectionFactory
{
private readonly IContentTypeRepository _repo;
public ContentTypeSelectionFactory(IContentTypeRepository repo)
{
_repo = repo;
}
public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
{
return _repo.List()
.Select(r => new SelectItem() { Text = r.Name, Value = r.ID.ToString() });
}
}
//...
[Display(GroupName = Globals.GroupNames.SiteSettings)]
[EditorDescriptor(EditorDescriptorType = typeof(CollectionEditorDescriptor<ContentCreationRule>))]
public virtual IList<ContentCreationRule> ContentCreationRules { get; set; }
//...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment