Wednesday, May 28, 2008

Creating a Site Column and adding it to ContentType using Object Model

Here is an example, how to create a Site Column and add the Site Column to a Content Type.

public SPField AddField(string fieldDisplayName, SPFieldType fieldType, bool bRequired)
{
SPField field = null;
try
{
// get the parent web
SPWeb web = contentType.ParentWeb;

string fieldName = web.Fields.Add(fieldDisplayName, fieldType, bRequired);
web.Fields[fieldDisplayName].Group = "My Site Columns";
web.Fields[fieldDisplayName].Update(true);

field = web.Fields[fieldDisplayName];

// add a field link to the content type
contentType.FieldLinks.Add(new SPFieldLink(field));
contentType.FieldLinks[fieldDisplayName].Required = bRequired;
contentType.Update(true);
}
catch
{ }
return field;
}

No comments: