Don Carnage
Don Carnage

Reputation: 71

How to update a content type programmatically?

i want to modify the "Required" property of a field of a list which is associated to a content type. i've modified the content type and schema of the list, but the "Required" is still set to true, i want it to be optional.

Any idea ?

thanx

Upvotes: 0

Views: 9058

Answers (2)

Tom Vervoort
Tom Vervoort

Reputation: 5108

Try like this:

private void SetFieldRequired(SPList list, string field, string contentType, bool required)
{
    SPField fieldInList = list.Fields[field];
    fieldInList.Required = required;        
    fieldInList.Update();

    SPField fieldInContentType = list.ContentTypes[contentType].Fields[field];
    fieldInContentType.Required = required;
    fieldInContentType.Update();
}

Don't forget to add some exception handling.

Upvotes: 2

Hugo Migneron
Hugo Migneron

Reputation: 4907

If you created your list and content type programmatically (using XML files), there are a few places where you need to make the change :

  1. In your ContentType.CT.Columns.xml file (set the Required = "FALSE" attribute in the XML of your Field element).
  2. In your ContentType.CT.xml (set the Required = "FALSE" attribute in the XML of your FieldRef element)
  3. In the schema.xml of your list, if the section, find your field and set the attribute to false.

You seem to have done these things correctly. However, the schema.xml of the list is only used when the list is created. Therefore, if you changed the schema.xml and deployed it, but without deleting and re-creating the list, your changes will effectively be useless.

EDIT :

If you can't delete and re-create your list, you will have to write code that will do it programmatically (through a feature or the equivalent). This will do the trick :

   using (SPSite site = new SPSite("http://yoursite"))
    {
        using (SPWeb web = site.RootWeb)
        {
            SPList list = web.Lists.TryGetList("Your List");
            if (list != null)
            {
                SPField fld = list.Fields[SPBuiltInFieldId.RequiredField];
                fld.Required = false;
                fld.Update();
            }
        }
    }

Upvotes: 1

Related Questions