This project is read-only.

Need to detect OnInitializing for new content only...

Topics: Customizing Orchard
Aug 8, 2013 at 7:57 AM
I have a custom part that has from and to date fields. When creating a new content item that has this part attached, I wish to default the "from" date field to the date of the latest "to" date already stored in the db (looking at other content items with this part attached).

So in the OnInitializing code in the handler for this part, I access the content manager to run a query to select the contentitem with the latest to date. Something like...
            OnInitializing<MyPart>((context, part) =>
                var latestPart = _contentManager.Query<MyPart, MyPartRecord>().OrderByDescending(p => p.ToDate).Slice(0,1).FirstOrDefault();

                part.FromDate = latestPart.ToDate + 1;
My code isn't exactly as above - I default the from date to today if there's not yet any existing records in the db. So it works great the first time I add a record. The problem is once I have a record in the DB if I try to list the content items I get a stack overflow exception. This occurs because OnInitializing is called not only when creating a new record, but also when loading existing items. Of course, I then query for the latest content item with the same part, which then calls OnInitializing again...which then calls my query again...and so on and so on....until stack overflow.

So my question is, within the OnInitializing method, is there a way to detect that it's being called for a new item, rather than an item that is being loaded from the db?
Aug 8, 2013 at 9:47 AM
I worked around this being querying the part record directly from within the OnInitializing handler (ie. IRepository<MyPartRecord>) to find the latest date.