Home Change language: Register | Log in
Beta cloud
Improve your life online
Click to learn more
Click to learn more
Click to learn more

How to update a field from a content type?

Problem description

I have a SharePoint list with several different content types. Here I want to hide one field in new form in all content type. I'm trying to run this code:

using (SPSite site = new SPSite("http://dms/"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPField webField = MyFieldUtils.FindFieldByInternalName(web.Fields, "FieldName");
        if (webField != null)
        {
         webField.PushChangesToLists = true;
         webField.ShowInNewForm = false;
         webField.Update(true);
        }

        SPList list = MyListUtils.FindListByInternalName(web, "FieldName");
        if (list != null)
        {
         SPField field = MyFieldUtils.FindFieldByInternalName(list, "FieldName");
         if (field != null)
         {
            field.PushChangesToLists = true;
            field.ShowInNewForm = false;
            field.Update(true);
         }
        
         foreach (SPContentType ct in list.ContentTypes)
         {
            field = MyFieldUtils.FindFieldByInternalName(ct.Fields, "FieldName");
            if (field != null)
            {
             field.ShowInNewForm = false;
             field.Update();
            }
         }
        }
    }
}

And here in red line I got an exception:

This functionality is unavailable for fields not associated with a list

Above code updated only field in default content type.

Solution

After a lot of experiments I found a work arround of this problem. You cannot change a field retrieved from a content type. If you update a field retrieved from a list - it changes only default content type field. So, solution is to change default content type to another and repeat code again and again. And after last content type you have to restore default content type and problem will be solved.

Tags: Programming, SharePoint
Created on: 2013-11-14 10:44:52
Updated on: 2013-11-14 10:47:57