BlogUmbraco and Things
Event Handlers & Media Folders
Author: Nigel Wilson
Posted: 3 November 2010
I am currently redeveloping a site for a Digital Photography
club. At the moment it is Joomla based, but the time has come to
convert it to Umbraco.
The club runs online photo competitions whereby all members will
be able to upload 3 images to the competition.
They run 10 competitions a year and so the solution within Umbraco
will be to have a parent node of "Competitions" and then the
website administrator will create child nodes for each
competition.
To keep things simple I wanted the administrator to only ahve to
create the content node and automagically a media folder created
and linked to the content node via a property within the document
type.
So enter stage right: Event Handlers
The following is some prototype code that achieves just
that.
using System;
using System.Collections.Generic;
using System.Text;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.media;
namespace UmbracoNewMediaFolderOnSave
{
public class AddMediaFolderHandler : ApplicationBase
{
public AddMediaFolderHandler()
{
Document.BeforePublish += new
Document.PublishEventHandler(Document_BeforePublish);
}
void Document_BeforePublish(Document sender,
umbraco.cms.businesslogic.PublishEventArgs e)
{
if (sender.ContentType.Alias == "memberCompetition")
{
Media m =
Media.MakeNew(sender.Text,MediaType.GetByAlias("Folder"),
User.GetUser(0), 1078);
sender.getProperty("mediaNodeID").Value =
m.Id.ToString();
sender.Save();
}
}
}
}
In the above I have hard coded the parent Media Node (1078),
however this could be referenced from an Application setting within
the web.config file - this is what I will look to do once I have
further refined my code.
Also note there is a property named "mediaNodeID" on the
respective memberCompetition document type.
So this is a quite simple example, however I feel it could be
useful for others as this type of situation could prove reasonably
common.
The next steps for me is to create a front end file upload page
that uploads images into the media folder of the chosen
competition.
Happy coding
Nigel
No comments recorded for post.