简体   繁体   中英

Create folder in umbraco - Umbraco 7

I have project in umbraco 7.4.3. I need to create media folder programmatically for each specific object that i create in the umbraco back office.

For example: i create hotel in the back office and i go to my overload of the function "Umbraco.Core.Services.ContentService.Saved" inside this function i'm trying to create media folder (same name as my new hotel name) under existing media folder named "hotels" for put inside the hotel images.

在此处输入图片说明

Don't overload any of the service functions. You should instead create a class derived from ApplicationEventHandler and override the ApplicationStarted method. In there, you can attach to the ContentService.Saving (or Saved ) event, and then create your Media item directly using Services.Media.CreateMedia() . See https://our.umbraco.org/documentation/Reference/Events/ for more details.

eg:

using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;

namespace MyProject.EventHandlers
{
    public class RegisterEvents : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            //Listen for when content is being saved
            ContentService.Saving += ContentService_Saving;     
        }

        /// <summary>
        /// Listen for when content is being saved, check if it is a new
        /// Hotel item and create new Media Folder.
        /// </summary>
        private void ContentService_Saving(IContentService sender, SaveEventArgs<IContent> e)
        {                
            IMedia parentFolder; // You need to look this up.
            foreach (var content in e.SavedEntities
                //Check if the content item type has a specific alias
                .Where(c => c.Alias.InvariantEquals("Hotel"))
                //Check if it is a new item
                .Where(c => c.IsNewEntity()))
            {
                Services.Media.CreateMedia(e.Name, parentFolder, "Folder");
            }
        }
    }
}

Note: I haven't tested this code; you'll likely need to debug it; and it's up to you to specify the parent folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM