Search code examples
c#episerver

Update ReadOnly Property during EventsPublishedContent


First, I want to add a readonly type property to my page type, is this possible? What I want is a string property that can be updated programatically, but not through the UI, and I would like the content editor to be able to see the value but not change it.

Assuming that is possible how do I update this property value during the Publish Event.

So how do I...

private void EventsPublishedContent(object sender, ContentEventArgs e)
{
    if (e.Content is MyPageType)
    {
         var myvalue = BusinessLogic.PerformAction(e.content)

         // Now I want to save myvalue on to a property in 
         // e.content.myProperty
    }
}

Solution

  • Please don't ask multiple questions on the same topic on stackoverflow

    ReadOnly

    Readonly properties are created using either the [ReadOnly(true)] or [Editable(false)] annotations.

    Events

    What you are looking for is the PublishingContent event. There are many ways to configure this

    Most basically need to tell Episerver in an initialization module that you want an event connected to a specific action on a specific IContent-type.

    From Episerver World

    [InitializableModule]
    [ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
    public class ContentEventHandler : IInitializableModule
    {
        public void Initialize(InitializationEngine context)
        {
            var eventRegistry = ServiceLocator.Current.GetInstance<IContentEvents>();
    
            eventRegistry.PublishingContent += OnPublishingContent;
        }
    
        private void OnPublishingContent(object sender, ContentEventArgs e)
        {
            if (e.Content.Name.Contains("BlockType"))
            {
                e.Content.Name = e.Content.Name.Replace("BlockType", "NewName");
            }
        }
    }
    

    Now this is ofcourse very primitive, typically I implement Alf Nilsson's EPiEventHelper. This way you will get a generic way to implement the event handling

    Snippet from https://talk.alfnilsson.se/2017/01/11/episerver-event-helper-v3-0/. This is also where you can learn more about the event helper

    [ServiceConfiguration(typeof(IPublishingContent))]
    public class PublishingStandardPage : PublishingContentBase<StandardPage>
    {
        protected override void PublishingContent(object sender, TypedContentEventArgs e)
        {
            // Here you can access the standard page
            StandardPage standardPage = e.Content;
        }
    }