Luis Valencia
Luis Valencia

Reputation: 34028

Add field to content type in specific position

The code below is working perfect, however I need the new field to be in the 5th position, and not at the end in the forms.

Any idea how?

private void UpdateDossierContentType(SPWeb parentWeb)
{
    SPList productList = parentWeb.Site.RootWeb.Lists["Product"];
    SPFieldLookup lookup = CreateLookupField("ProductNameLookup", "CustomGroup",
            false, false, parentWeb.Site.RootWeb,
            parentWeb.Site.RootWeb.Lists["Product"],
           productList.Fields["Product Name"].InternalName);
   LinkFieldToContentType(parentWeb.Site.RootWeb, "Dossier", (SPField)lookup);

    //SPContentType dossierCT = productList.ContentTypes["Dossier"];
    //dossierCT.DeleteFieldRefFromContentType(parentWeb.Fields["Product"]);
    //dossierCT.Update();
}

public static void LinkFieldToContentType(SPWeb web, string contentType, SPField field)
{
    SPContentType ct = web.ContentTypes[contentType];
    ct.FieldLinks.Add(new SPFieldLink(field));
    ct.Update(true);
}

public static SPFieldLookup CreateLookupField(string fieldName, string group, bool required, bool allowMultipleValues, SPWeb w, SPList lookupList, string lookupField)
{
    w.Fields.AddLookup(fieldName, lookupList.ID, lookupList.ParentWeb.Site.RootWeb.ID, required);
    SPFieldLookup lookup = (SPFieldLookup)w.Fields[fieldName];
    lookup.AllowMultipleValues = allowMultipleValues;
    lookup.LookupField = lookupField;
    lookup.Group = group;
    lookup.Update(true);
    return lookup;
}

Upvotes: 2

Views: 1403

Answers (1)

Aquila Sands
Aquila Sands

Reputation: 1471

Use ct.FieldLinks.Reorder(stringArrayOfInternalFieldNames) see MSDN SPFieldLinkCollection.Reorder

Upvotes: 1

Related Questions