1
votes

Using the Sitecore event handler 'OnItemSave', I am adding an English language verison of the item if it does not exist.

public void OnItemSaved(object sender, EventArgs args)
{
    var item = Event.ExtractParameter<Item>(args, 0);
    if (item == null) return;
    //Add version of item in English
    if (Sitecore.Context.Database.GetItem(item.ID, Sitecore.Data.Managers.LanguageManager.GetLanguage("en")) == null)
    using (new LanguageSwitcher("en"))
       {
         item.Versions.AddVersion(); 
       }
}

But this does not add the version in the en language, it adds it in the Content Language.

1

1 Answers

5
votes

From what I remember, when you call:

Item enItem = Sitecore.Context.Database.GetItem(item.ID, Sitecore.Data.Managers.LanguageManager.GetLanguage("en"))

and if there no en version but this item has version in ANY other language, you will still get an Item object but enItem.Versions.Count will be 0.

You should try something like that (not tested!):

Item enItem = Sitecore.Context.Database.GetItem(item.ID, Sitecore.Data.Managers.LanguageManager.GetLanguage("en"))
if (enItem.Versions.Count == 0)
{
    using (new LanguageSwitcher("en"))
    {
        enItem.Editing.BeginEdit();
        enItem.Versions.AddVersion();
        enItem.Editing.EndEdit();
    }
}

EDIT If you need to copy fields from the original item to EN item:

  1. Item newEnVersion = enItem.Versions.AddVersion();
  2. item.Fields.ReadAll()
  3. foreach (Field field in _item.Fields) { if (field != null && !string.IsNullOrEmpty(_item[field.Key])) { newEnItem[field.Key] = _item[field.Key] } }