3
votes

I am trying to create a sitecore item programmatically. All working good. But the item I am creating from is in language "EN-GB" but new item created is in language "EN". Is there a way I can set the language value while creating an item.

var currentDatabase = Sitecore.Configuration.Factory.GetDatabase(selectedItem.Database.Name);

    if (currentDatabase != null)
    {
        var rootItem = currentDatabase.GetItem(RootItemPath);

        if (rootItem != null)
        {
            //Create new item
            var item = rootItem.Add(selectedItem.Name, CommunityProjectTemplateId);

            if (item != null)
            {
                item.Fields.ReadAll();
                item.Editing.BeginEdit();

                try
                {
                    //Add values for the fields
                    item.Fields["Overview Body Content"].Value = selectedItem.GetStringField("ProjectOverview");
                }
                catch (Exception)
                {
                    item.Editing.EndEdit();
                }
            }
        }
    }
3

3 Answers

11
votes

You need to switch the context language before you retrieve the root item.

using (new LanguageSwitcher("en-gb"))
{
    var rootItem = currentDatabase.GetItem(RootItemPath);
    var item = rootItem.Add(selectedItem.Name, CommunityProjectTemplateId);

    // Do your editing on item here...
}
5
votes

If you are trying to add an item in en-GB then make sure that the "Root Item" that you get is in en-GB by doing this.

Language language;
Language.TryParse("en-GB", out language);
var rootItem = currentDatabase.GetItem(RootItemID, language);

After that if you try to add an item it will be in that language. Using the Language Switcher is a great idea as well but be careful when changing language context.

1
votes

You can use the following code before creating an item

var language = Sitecore.Globalization.Language.Parse( "en-GB" );    

Sitecore.Context.SetLanguage( language, true );

The last line will set the context language to en-GB. Then the item will be created with that language version.