Add a multilingual field to SharePoint through code

I will explain how to add a multilingual field with codebehind because this is quite tricky…

Let’s say you want to add a field ‘Client’ when a certain feature is activated. A reason for this to be in codebehind could be that this feature already existed and you’re writing an update. So you want the field to be added to exisitng lists aswell. And ofcourse for Dutch users it should read ‘Klant’.

So here is the code to show you how to add a multilingual field (sorry, for the layout wordpress is not so code friendly (or do enlighten me 😉 )):

SPWeb rootWeb = site.RootWeb;
string internalFieldName = “MyCustomClientField”;
//Check if field already exists
if (!rootWeb.Fields.ContainsFieldWithStaticName(internalFieldName)){
//If you activate this feature on an English site which has the multilanguage
//enabled
  and you happen to be in the Dutch UIculture, the titles and
//descriptions not are set correctly(!)
CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = newCultureInfo((int)web.Language);
rootWeb.Fields.Add(internalFieldName, SPFieldType.Text, false);
SPField clientField = rootWeb.Fields[internalFieldName];
clientField.Title =“$Resources:TweeAT.Example,ClientFieldTitle”;
clientField.Description =“$Resources:TweeAT.Example,ClientFieldDescription”;     clientField.Update();
// 1033 is “en-US” and 1043 is “nl-NL”
List<uint> supportedLcids = newList<uint>() { 1033, 1043 };
foreach (uint lcid in supportedLcids) {
clientField.DescriptionResource.SetValueForUICulture(newCultureInfo((int)lcid), GetSharePointResource(“ClientFieldDescription”, lcid));
clientField.DescriptionResource.Update();
clientField.TitleResource.SetValueForUICulture(newCultureInfo((int)lcid), GetSharePointResource(“ClientFieldTitle”, lcid));
clientField.TitleResource.Update();
}
//reset to current
Thread.CurrentThread.CurrentUICulture = currentCulture;

And my GetSharePointResource method looks like this:

public static string GetSharePointResource(string key, uint language) {
return SPUtility.GetLocalizedString( string.Format(“$Resources:TweeAT.Example,{0};”, key),“TweeAT.Example”, language);
}

For more about where and how to add resource (.resx) files in SharePoint, see my earlier post:
https://carolinepoint.wordpress.com/2011/01/18/sharepoint-2010-solutions-resources/

I hope that saved you a lot of frustration! Any feedback or comments are appreciated!

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: