Sorting children on ContentSavedNotification

, , , ,

In v8 you could use the IContentService to sort the children in a container when triggering an event from the backoffice.

This would sort all items in a news container when saving a child, as an example:


private void OnSaved(IContentService sender, SaveEventArgs<IContent> args)
{
    foreach (var node in args.SavedEntities)
    {
        if (node.ContentType.Alias == "NewsModel")
        {
            sender.Sort(node.Parent().Children().OrderBy(n => n.Name), 0, false);

            return;
        }
        return;
    }
}

I can’t figure out how to accomplish the same thing in vNext (currently on v13).
Is there a way for me to sort the children in a IContent node?

private void SortContainerChildrenByName(ContentSavedNotification notification)
 {
     foreach (var node in notification.SavedEntities)
     {
         if (node.ContentType.Alias == NewsModel.ModelTypeAlias)
         {
             var parent = _contentService.GetById(node.ParentId);
             //now what?
             
             return;
         }

         return;
     }
 }

Please point me i the right direction!
Cheers’

Hi Anders,

I think you are looking for the .Sort function on the IContentService. This allows you to pass the ids of the items in the order that you want them to be in.

1 Like

I always have this page bookmarked. Is the sort of javascript equivalent of Linq expressions:

1 Like

Of course, thank you!
But how do i get the Children from parent (IContent), as in v8?

You can either call the .GetChildren function located in the ContentService or you set up a umbraco context and do something like this:

using var ctx = _umbracoContextFactory.EnsureUmbracoContext();
var children = ctx.UmbracoContext.Content!.GetById(parentId).Children()

Taken from the full file here (https://github.com/patrickdemooij9/CardGameDBSites/blob/63746877f2568f3570877385c6209bf16c81fb32/SkytearHorde.Website/EventHandlers/CardSortingEventHandler.cs#L16).

Differences between the two are: ContentService will always call the database while the UmbracoContext will also try to get them from the cache first.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.