tags:

views:

30

answers:

2

Hi,

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

+1  A: 

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();
            }
        }
    }
Hugo Migneron
Thank you for your answer ... but we already did the "trick" in the FeatureReceiver of the list, in FeatureActivated method precisely, but when adding or editing an item of the list, the field is still required :-(
Don Carnage
+1  A: 

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.

Tom Vervoort
Thank you, i've changed your code a little bit and it seems to work great ! The update() method must be called on the content type not the field.SPField fieldInContentType = list.ContentTypes[contentType].Fields.GetFieldByInternalName(field);fieldInContentType.Required = false;list.ContentTypes[contentType].Update();
Don Carnage
Sorry for the mistake, I didn't test this code. :-)
Tom Vervoort