Copied to clipboard

Flag this post as spam?

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


  • Josefine 28 posts 140 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
    15 days ago
    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.

Please Sign in or register to post replies

Write your reply to:

Draft