Howto programatically set a block name

Vote:
 

When you create an instance of a block in the CMS, you give it a name, which defaults to something like "new block 1" and you can set the blocks properties  (e.g. "SKU" and "Country")

When the block is saved or edited in the CMS, we want to programatically set or change the blocks name to be a function of the properties, e.g. "Country-SKU" e.g. "UK-1234".

When you defined a block in code, you dont need to define a controller.  I am guessing there is a way to create a block controller which handles saving?

Does anyone have an example of this?

#224653
Jun 24, 2020 7:42
Vote:
 

Acting on events in Episerver (such as content being saved) is performed by attaching an event handler to the appropriate event using an instance of IContentEvents, typically from within an IInitializableModule. There's a load of events to choose from but it sounds like you're after the SavingContent Event which fires as content is about to be saved. One thing to bear in mind is that, when you tie into an event, your handler is run each time that event is fired regardless of the content which has triggered the event so, in your scenario, you'd need to ensure you're checking the type of the content before setting the name. A basic implementation looks a bit like this:

[InitializableModule]
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class PageEventInit : IInitializableModule
{
    public void Initialize(InitializationEngine context)
    {
        //Attach the event when the site initialises
        context.Locate.ContentEvents().SavingContent += ContentSaving;
    }

    private void ContentSaving(object sender, ContentEventArgs e)
    {
        //Check the content is the type we're interested in
        if (e.Content is MyContentType content)
        {
            content.name = content.sku;
        }
    }

    public void Uninitialize(InitializationEngine context)
    {
        //Remove the event on uninitialisation
        context.Locate.ContentEvents().SavingContent -= ContentSaving;
    }
}

One additional thing to note - In this instance, as we've tied into the ContentSaving event our e.Content is writable. In other events (e.g. ContentSaved) it wouldn't be so you'd need to create a writable clone inorder to modify it.

#224681
Jun 24, 2020 8:32
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.