0

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
codeulike
  • 22,514
  • 29
  • 120
  • 167

1 Answers1

1

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")

spmason
  • 4,048
  • 2
  • 24
  • 19
  • Thanks, I guess for the SetDetail technique to work the property will have to have an `Editable...` attribute so that the edit engine calls the setter. That makes it a bit ugly in the case of UserIDs that you don't necessarily want to display to content editors (or allow them to edit). Overriding the AddTo method with an ID check sounds good though, I'll look into that. – codeulike Nov 03 '10 at 15:42
  • You don't need the Editable attribute for the value to be saved - Editable just adds some "magic" to allow the admin UI to display the correct edit control – spmason Nov 11 '10 at 15:25