Using the Sitecore item:saved
event handler, I am trying to add items in other languages. So if you say, add a item in one language, it should automatically add the item in the other given languages when saved.
Right now, I can get all the languages from the master database. The problem is when adding a new version of the new language, it triggers itself and therefore recursive adds "infinite" new elements until it crashes. How is it possible to bypass this?
public void OnItemSaved(object sender, EventArgs args)
{
Item savedItem = Event.ExtractParameter(args, 0) as Item;
if (savedItem.Versions.Count == 1)
{
// Allow only non null items and allow only items from the master database |
if (savedItem != null && savedItem.Database.Name.ToLower() == "master")
{
// Do some kind of template validation to limit only the items
if (savedItem.TemplateID == ID.Parse("{template id}"))
{
// Get all the installed languages from the master database
var installedLanguages = LanguageManager.GetLanguages(Database.GetDatabase("master"));
// Go through every language in the list
foreach (var language in installedLanguages)
{
// Copy item to the new language
if (savedItem.Language.Name != language.Name)
{
using (new LanguageSwitcher(language.Name))
{
// Save the new item, but it fails since it triggers itself (the event)
savedItem.Versions.AddVersion();
}
}
}
}
}
}
Try this code:
foreach (var language in installedLanguages)
{
if (savedItem.Language.Name != language.Name)
{
var otherLanguageItem = savedItem.Database.GetItem(savedItem.ID, language);
if (otherLanguageItem.Versions.Count == 0)
{
otherLanguageItem.Versions.AddVersion();
}
}
}