By admin • November 28, 2022
Our client requested to implement a handler, which will automatically publish the media library, when content editor upload it. It happens that often Content Editors just forgot to publish the item.
Once the content editor upload the image, the OnItemSaved handler will fire, and will call the code below, which will publish to web immediately.
Note: If Content Editor decides to change the order, do sorting or so for Media Library, it will trigger huge publishing job.
The code bellow:
public class MediaItemEventHandlers
{
public void OnMediaItemSaved(object sender, EventArgs args)
{
if (args != null)
{
// Get the item being saved.
var item = Event.ExtractParameter(args, 0) as Item;
if (item != null)
{
using (new SecurityDisabler())
{
if (item.Paths.IsMediaItem)
{
// Automatically publish the media item.
this.PublishItem(item, "web");
}
}
}
}
}
private void PublishItem(Item item, string targetDbName)
{
if (item != null)
{
try
{
var sourceDb = Factory.GetDatabase("master");
var targetDb = Factory.GetDatabase(targetDbName);
if (sourceDb != null && targetDb != null)
{
var options = new PublishOptions(sourceDb, targetDb, PublishMode.SingleItem, item.Language, DateTime.Now)
{
RootItem = item,
Deep = true
};
var publisher = new Publisher(options);
publisher.PublishAsync();
}
}
catch (Exception e)
{
Sitecore.Diagnostics.Log.Info("Database not present " + targetDbName, this);
}
}
}
}
And the config file
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<events timingLevel="custom">
<event name="item:saved">
<handler type="MyNamespace.Utility.MediaItemEventHandlers, MyNamespace" method="OnMediaItemSaved" />
</event>
</events>
</sitecore>
</configuration>