Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Odd Veibust 5 posts 27 karma points
    Nov 26, 2014 @ 12:41
    Odd Veibust
    0

    Setting SortOrder when entity is saved

    Is there a proper way of setting SortOrder on a new entity when saving it in Umbraco 7.1.8?

    Default the SortOrder is set to the highest number +1 when a new entity is saved, but I want it to have the lowest -1, so that the entity will be the first in the list.

    I have tried to set it on the events Created and Saving, but it seems to be overwritten when Saved.

    I have solved it for now with the code below, but I wonder if there is a better way/best practice to do it?

            void ContentService_Saved(IContentService sender, Umbraco.Core.Events.SaveEventArgs e)
            {
                var contentTypes = new List() { "Nyhet", "Rundskriv", "Sirkulaere" };
                if (e.SavedEntities.Count() == 1)
                {
                    var entity = e.SavedEntities.First();
                    if (entity.IsNewEntity() && contentTypes.Contains(entity.ContentType.Alias))
                    {
                        var parentEntity = entity.Parent();
                        if (parentEntity != null)
                        {
                            entity.SortOrder = parentEntity.Children().OrderBy(n => n.SortOrder).First().SortOrder - 1;
                            if (entity.Published)
                            {
                                sender.SaveAndPublishWithStatus(entity, 0, false);
                            }
                            else
                            {
                                sender.Save(entity, 0, false);
                            }
                        }
                    }
                }
            }
Please Sign in or register to post replies

Write your reply to:

Draft