Sunday, October 13, 2013

C# code to create Site Column, Content Type, and add fields to Content Type

You can use below code to create following:-
1. Site Columns
2. Content Types
3. Add Fields to Content Type


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;


namespace LAB
{
    public static class SPDevUtility
    {
        public static SPContentType CreateSiteContentType(SPWeb web, string contentTypeName,
        SPContentTypeId parentItemCTypeId, string group)
        {
            if (web.AvailableContentTypes[contentTypeName] == null)
            {
                SPContentType itemCType = web.AvailableContentTypes[parentItemCTypeId];
                SPContentType contentType =
                    new SPContentType(itemCType, web.ContentTypes, contentTypeName) { Group = @group };
                web.ContentTypes.Add(contentType);
                contentType.Update();
                return contentType;
            }
            return web.ContentTypes[contentTypeName];
        }

        public static SPField CreateSiteColumn(SPWeb web, string displayName,
            SPFieldType fieldType, string groupDescriptor)
        {
            if (!web.Fields.ContainsField(displayName))
            {
                string fieldName = web.Fields.Add(displayName, fieldType, false);
               
                SPField field = web.Fields.GetFieldByInternalName(fieldName);
               
                field.Group = groupDescriptor;
               
                field.Update();

                return field;
            }

            return web.Fields[displayName];
        }

        public static void AddFieldToContentType(SPWeb web, SPContentTypeId contentTypeId, SPField field)
        {
            SPContentType contentType = web.ContentTypes[contentTypeId];

            if (contentType == null) return;

            if (contentType.Fields.ContainsField(field.Title)) return;

            SPFieldLink fieldLink = new SPFieldLink(field);

            contentType.FieldLinks.Add(fieldLink);

            contentType.Update();
        }
    }
}

3 comments:

  1. How can we add to all content types?

    ReplyDelete
  2. You would need to provide content type ID and other params to below method

    public static void AddFieldToContentType(SPWeb web, SPContentTypeId contentTypeId, SPField field)
    {
    SPContentType contentType = web.ContentTypes[contentTypeId];

    if (contentType == null) return;

    if (contentType.Fields.ContainsField(field.Title)) return;

    SPFieldLink fieldLink = new SPFieldLink(field);

    contentType.FieldLinks.Add(fieldLink);

    contentType.Update();
    }

    ReplyDelete