Showing posts with label ContentTypes. Show all posts
Showing posts with label ContentTypes. Show all posts

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;
}

Creating ContentType using Object Model

Here is an example, how to create an custom content type and add to custom group in Site Content Types.

SPContentType contentType = new SPContentType(
web.AvailableContentTypes["document"], web.ContentTypes,"sampleContentType");
contentType.Group = "My Content Types";
contentType.Description = "Creating Content Types using Object Model";
web.ContentTypes.Add(contentType);