Copied to clipboard

Flag this post as spam?

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


  • Josefine 30 posts 143 karma points
    Dec 13, 2024 @ 10:17
    Josefine
    0

    Is it possible to change so that the most recently uploaded image/document appears at the top of the Media folder in Umbraco?

    Hi

    When I upload a new image in Umbraco, the new image is placed at the bottom of the folder in the tree structure. Can I change how it sorts?

    I know I can manually sort it in Umbraco, but I want it to be automatic when I upload images to a folder in Media.

    Best regards, Josefine

  • Midhun Roy 2 posts 72 karma points
    Jan 03, 2025 @ 07:15
    Midhun Roy
    0

    Hi,

    I think, in this case, we need to create a custom event handler, which will automatically reorder the media items whenever new media is uploaded or saved.

    For example:

    using Umbraco.Cms.Core.Events;
    using Umbraco.Cms.Core.Notifications;
    using Umbraco.Cms.Core.Services;
    using Umbraco.Cms.Core.Web;
    
    public class MediaSavedEventHandler : INotificationHandler<MediaSavedNotification>
    {
        private readonly IMediaService _mediaService;
    
        public MediaSavedEventHandler(IMediaService mediaService)
        {
            _mediaService = mediaService;
        }
    
        public void Handle(MediaSavedNotification notification)
        {
            foreach (var media in notification.SavedEntities)
            {
                if (media.ParentId > 0) // Ensure the media is inside a folder
                {
                    var siblings = _mediaService.GetPagedChildren(media.ParentId, 0, int.MaxValue, out _)
                                                .OrderByDescending(m => m.CreateDate); // Sort by creation date, descending
    
                    int sortOrder = 0;
                    foreach (var sibling in siblings)
                    {
                        if (sibling.SortOrder != sortOrder)
                        {
                            sibling.SortOrder = sortOrder;
                            _mediaService.Save(sibling); // Save without triggering events
                        }
                        sortOrder++;
                    }
                }
            }
        }
    }
    

    Then register the event handler in the Startup.cs file or the Program.cs.

    Example for registering the event handler in Program.cs

    builder.Services.AddUmbraco(builder.Configuration)
        .AddBackOffice()
        .AddWebsite()
        .AddComposers()
        .AddNotificationHandler<MediaSavedNotification, MediaSavedEventHandler>() // Register the event handler
        .Build();
    

    FYI: I got the above solution from ChatGPT.

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies