Adding Field to Content Type Programmatically
The following sample code add field to the content type programmatically. The field has to be created as site column first refer to my first blog for how to add field programmatically. It's not really the field that's added to the content type but a reference of the field (It's the same as fieldRef attribute in feature elements xml).
SPSite site = new SPSite (_siteUrl)
PublishingSite pubSite = new PublishingSite(site);
SPContentType contentType = pubSite.ContentTypes[contentTypeName];
SPField field = pubSite.RootWeb.Fields[fieldGuid];
SPFieldLink fieldLink = new SPFieldLink(field);
contentType.FieldLinks.Add(fieldLink);
contentType.Update(true);
Later on if you want to update the FieldLinks (fieldRef), you can get the FieldLink for the field by the same fieldGuid. The following code sample shows how to return the SPFieldLink from content type.
foreach (SPFieldLink fieldRef in contentType.FieldLinks)
{
if (fieldRef.Id == fieldGuid)
return fieldRef;
}
SPSite site = new SPSite (_siteUrl)
PublishingSite pubSite = new PublishingSite(site);
SPContentType contentType = pubSite.ContentTypes[contentTypeName];
SPField field = pubSite.RootWeb.Fields[fieldGuid];
SPFieldLink fieldLink = new SPFieldLink(field);
contentType.FieldLinks.Add(fieldLink);
contentType.Update(true);
Later on if you want to update the FieldLinks (fieldRef), you can get the FieldLink for the field by the same fieldGuid. The following code sample shows how to return the SPFieldLink from content type.
foreach (SPFieldLink fieldRef in contentType.FieldLinks)
{
if (fieldRef.Id == fieldGuid)
return fieldRef;
}
Comments