Monday, 6 May 2013

How to change the display name of OOB field "Title" using object model


Hello All,

Today I am going to post small and very simple post – “How to change the display name of OOB field "Title" using object model”. Since I struggled for some time to change the display name of OOB title column in one of the my custom list I thought I should share this J

In our project we have our custom list and list content type is derived from ITEM content type (0x01). So we have Title column from ITEM content type. But customer want to change the display name of Title column say “Customer Title”. So I thought I will simply do this change in my content and it will work like 

<FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" DisplayName="Customer Title" Required="TRUE"/>

But unfortunately it didn’t work. I did some research, some blogs says that change the display name in Schema.xml of list definition in <Fields> section for Title field but for us this is also not a solution since we have created our list using object model in FeatureActivated() of  our feature receiver. Again did some research and able to change the display name of OOB title column.  We could do this by updating “Title” property of respective SPField instance.

Following is the sample code

if (list.Fields.ContainsField("Title"))
                        {
                            SPField fldTitle = list.Fields["Title"];
                            fldTitle.Title = “My Custom DisplayName”;
                            fldTitle.Update(true);
                       
                        }

and following is the full code.

public class MyCustomerEventReceiver : SPFeatureReceiver
{

        #region Overload Methods
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            if (site != null) {
                SPWeb web = site.RootWeb;
                SPList list = web.Lists.TryGetList(“My Custom List”);
                bool flag = web.AllowUnsafeUpdates;
                    if (list == null)  {
                        web.AllowUnsafeUpdates = true;

Guid guid = web.Lists.Add(My Custom List, "Custom List", SPListTemplateType.GenericList);
                       
list = web.Lists[guid];
                       
                        if (list.Fields.ContainsField("Title"))
                        {
                            SPField fldTitle = list.Fields["Title"];
                            fldTitle.Title = “My Custom DisplayName”;
                            fldTitle.Update(true);
                       
                        }
list.Update();
}
              }
}

}

Thanks!

Enjoy reading J

Feel free to comment / feedback if any or if you have any query J



No comments: