Ordering ContentArea block items by StartPublish Date

Vote:
 

Hi, 

I would like the ability to order block items (ContentAreaItem) within a content area by published date (StartPublish). I am adding a new bool 'Order Items' to the model and if true I want to apply the order as opposed to the default sort order in which content has been created within the content area. 

From my initial look it seems that i need to cast the ContentAreaItem to an IVersionable in order to access the StartPublish property value. I achieved this as follows, it returns an IEnumerable<IVersionable> collection (The reason for loading 'BlockData' is because there are three different types that are allowed to be created)

var items = block.ContentItemArea.FilteredItems.Select(i => contentLoader.Get<BlockData>(i.ContentLink) as IVersionable);

if (block.OrderItems)
{
    items = items.OrderByDescending(x => x.StartPublish);
}

What is the best way to cast an IVersionable type back into a ContentAreaItem so that i can add them into a ContentArea and use the @HtmlPropertyFor helper in the view to render the items out ? One approach i looked into was to loop through the items in the IVersionable collection and using new ContentAreaItem() { ContentGuid = item.ContentGuid, ContentLink = item.ContentLink }; but i am unsure if this is the correct approach. 

Im hoping i have missed something obvious and there is a straight forward way of achieveing this :)

Thanks 

Paul

#223958
Edited, Jun 08, 2020 15:55
Vote:
 

Hi Paul,

At it's simplest you can just do:

var contentAreaItem = new ContentAreaItem { ContentLink = item.ContentLink };

If the editors are using Display Options you'll also need the RenderSettings from the original ContentAreaItem.

#223959
Jun 08, 2020 14:22
Vote:
 

Hi Jake,

Yeah, this is pretty much where im at with it to be honest. I just thought i might be missing an easier way than having to new up the ContentAreaItem to get them back in. Display options was something i was going to look into to ensure that nothing is missed.

Thanks for the response!

Paul

#223960
Edited, Jun 08, 2020 15:43
Vote:
 

Hi Paul,

As a thought, could you not just retain a reference to your original ContentAreaItem by doing something like this:

var items = currentPage.MainContentArea.FilteredItems
    .Select(x => new KeyValuePair<DateTime, ContentAreaItem>((x.GetContent() as IVersionable).StartPublish ?? DateTime.MaxValue, x))
    .OrderBy(x => x.Key)
    .Select(x => x.Value);
#224018
Jun 09, 2020 12:15
Vote:
 

Hey Paul, 

Apologies i missed your response! Thank you for providing an answer.

We have implemented your suggestion, this feels much better to me so thank you very much :)

Thanks 

Paul

#224593
Jun 23, 2020 8:26
* 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.