0
votes

How do i create a Field value for a Particular Item in a Particular Language? I have an Excel that has all the item Names inside the RootItem .These Items exist in a en-US language Already. i need add values for a particular field for other languages.. Like en-GB, nl-NL, it-IT.

I have a List like

ItemName          Language              Translation
TestItem              en-GB                    Hello
TestItem              nl-NL                      Hallo
and so on..

The only problem is, when i do item.Add, it creates a new item rather than adding the value to the existing item. How can i handle this?

My code is as follows:

foreach (DataRow row in dt.Rows)
{
   Language language = Language.Parse(languageId);
   var rootItem = currentDatabase.GetItem(RootItemPath, language); 
   var item = rootItem.Add(itemName, templateItem);
   if (item != null)
   {               
       item.Fields.ReadAll();
       item.Editing.BeginEdit();

       try
       {
           //Add values for the fields
             item.Fields["Translation"].Value = strTranslationValue;
       }
       catch (Exception)
       {
          item.Editing.EndEdit();
       }
    }
}
2

2 Answers

1
votes

You need to switch the language before you get the root item:

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

    // Add new item here...
}
1
votes

Try This:

var rootItem = currentDatabase.GetItem(RootItemPath); 
foreach (DataRow row in dt.Rows)
{
   Language language = Language.Parse(languageId);

   var itemInCurrentLanguage = rootItem.Children.Where(i=>i.Name == itemName).FirstOrDefault();

   if(itemInCurrentLanguage == null){
       itemInCurrentLanguage  = rootItem.Add(itemName, templateItem);
   }

   var itemInDestinationLanguage = currentDatabase.GetItem(itemInCurrentLanguage.ID, language );

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

       try
       {
           //Add values for the fields
             itemInDestinationLanguage.Fields["Translation"].Value = strTranslationValue;
       }
       catch (Exception)
       {
          //Log any error
       }
       finally
       {
          itemInDestinationLanguage.Editing.EndEdit();
       }
    }
}