Reputation: 336
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.
Upvotes: 2
Views: 1021
Reputation: 2316
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.
e.g.:
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.
Upvotes: 6