Search code examples
asp.netcontent-management-systemdefaultn2

N2: Set default values for ContentItems


When using N2 CMS:

If I want to set some default values when a new ContentItem is created (e.g. setting the CreatedByUser value for a new Page so I can record who originally created it) where is the best place to put that code?

I figure the constructor of the ContentItem isn't ideal because that will get called when existing objects are loaded.


Solution

  • If you're using the Get/SetDetail syntax then you can do something like this in the property getter:

    public virtual string TopImage
    {
        get { return (string)(GetDetail("TopImage") ?? string.Empty); }
        set { SetDetail("TopImage", value); }
    }
    

    That's a bit ugly, so there's also an overload for Get/Set detail that lets you specify the default:

    public virtual string TopImage
    {
        get { return GetDetail("TopImage", String.Empty /* Default */); }
        set { SetDetail("TopImage", value, String.Empty /* Default */); }
    }
    

    If you want to save a value when something is saved then try overriding the AddTo method on the ContentItem. This is called every time the object is saved, so be careful if you only want to call it the first time something is saved (ID == 0 when an Item is "new")