5

This should be super simple but for some reason I can't get it to work. I am writing code for migrating data and the items has several versions in both English and Swedish. For some reason I cannot get Sitecore to create a version in English. I'm obviously doing something wrong. I'm not able to track down what is causing it?

the migratedItem is the item I just migrated in Swedish and that I want to add a English version too.

Item englishItemVersion;
try
{
   using (new LanguageSwitcher("en"))
   {
      englishItemVersion = migratedItem.Versions.AddVersion();                    
   }
}
2

In your code, I can see that you are trying to add a new version of the item in the context language, as opposed to the language of the actual item. Remember that each instance of a Sitecore item is actually only a single language version of the item. Don't believe me? Have a look at your item.ItemUri and see for yourself!

In order to add a new language version to an item, the first thing that you need to do is get the item in the language that you wish to add a new version for. As such, if your code had been the following, it would have worked:

using (new LanguageSwitcher("en"))
{
   var migratedItem = Sitecore.Context.Database.GetItem(migratedItemId);
   englishItemVersion = migratedItem.Versions.AddVersion();                    
}

Of course, you can still do the above without a Switcher, if you want to:

var migratedItem = Sitecore.Context.Database.GetItem(migratedItemId, "en");
englishItemVersion = migratedItem.Versions.AddVersion();
|improve this answer|||||
  • This did the trick. Please note that the content editor has some sort of caching that can cause these kind of changes not to show up. That cost a couple of wasted hours before i figured out that the code was actually working, but i could not see the changes in content editor... – Troels Aaberg Nov 23 '16 at 13:30
4

Try something like this:

// get the item in en language - you should get the item but versions count should be 0
Item enItem = migratedItem.Database.GetItem(migratedItem.ID, enLanguage);

// edit the item and create a version
enItem.Editing.BeginEdit();
enItem.Versions.AddVersion();
enItem.Editing.EndEdit();
|improve this answer|||||
  • 3
    Great answer! Just to clarify though, you don't need to BeginEdit/EndEdit unless you plan to edit fields on the item, as well. – Zachary Kniebel Nov 22 '16 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.