Sitecore Language Switcher Gotcha

Not really a gotcha, but something I noticed the other day while hunting down a bug.

When you’re running in several languages, it’s easy to get your language switcher in the wrong place if you’re manipulating item data in code. For example:

            //Get the folder in the context language
            var item = db.GetItem(new ID("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"));

            //Switch to German
            using (new LanguageSwitcher(Language.Parse("de-DE")))
            {
                var childItem = item.Add("New Item", new TemplateID(new ID("{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}")));
                childItem.Editing.BeginEdit();
                childItem["Title"] = "Lorem Ipsum";
                childItem.Editing.EndEdit();
            }

What we see here (_is failure to communicate_) is that because we get the item in the context language, when we try to add a child item and set data in that item – despite switching to German, we’re adding an English version:

versions

This is because the parent item already has the context set as English – and that’s what’s used by the Sitecore Item API. Instead – you would want to move the GetItem in to the LanguageSwitcher using statement:

            //Switch to German
            using (new LanguageSwitcher(Language.Parse("de-DE")))
            {
                var item = db.GetItem(new ID("{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"));
                var childItem = item.Add("New Item", new TemplateID(new ID("{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}")));
                childItem.Editing.BeginEdit();
                childItem["Title"] = "Lorem Ipsum";
                childItem.Editing.EndEdit();
            }

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s