Create List Content Type and Its Field Using CSOM
Softree Technology > Blogs > SharePoint > Create List Content Type and Its Field Using CSOM

Create List Content Type and Its Field Using CSOM

  • Posted by: Softree Technology

In this article, we are going to discuss an important & mostly useful feature of SharePoint i.e., Content Type. As we all know that the content type is the set of columns that we can reuse in all lists and libraries in a site. We are going to create a List Content, its column & will add this content type to all custom lists present in the Site. Hence follow the below steps and code snippet to perform the above action.

Step 1:  Set the credential by giving input of user ID and Password for SharePoint.

Step 2 :  Using client context get the web.

Step 3 : The function CreateSpContentType () is used for the creation of List content type using the unique ID & Group. Here the title of the content type is set as “Employee Info”.

Step 4 : The function CreateSiteField () is used then to create the fields of the content type which will represent the employee details. First, we must create site columns & then we can add it to the content type fields.

Step 5 : After Creating the content type and its field, the function   AddContentType () is used to attach the content type with all available custom list in the site. 

In this function first, we have to get all custom lists present in the site by using the base id(for custom List the Base Id=100) & then for adding the content type into the list we have to get the content type by using its unique ID which we used previously while creating the content type. (The Property ContentTypesEnabled  should set to be true).

using System;
using System.Security;
using Microsoft.SharePoint.Client;

namespace Createcontenttype
{
   class Program
   {
      static void Main(string[] args)
      {
        #region [Variables]

        string username = string.Empty;
        string password = string.Empty;
        #endregion

        #region [SP Variables]           
        Web spWeb = null;           
        ContentType contentType = null;
        #endregion

        using (ClientContext context = new ClientContext(https://sharepoint.com/site))  //Enter the site url  
        {
            SecureString securstr = new SecureString();
            password = "1234@abc";//Enter the password
            foreach (char ch in password)
            {
                securstr.AppendChar(ch);
            }
            context.Credentials = new SharePointOnlineCredentials("user.onmicrosoft.com", securstr);//Enter the user id
            spWeb = context.Site.RootWeb;
            context.Load(spWeb);
            context.Load(context.Web);
            contentType = CreateSpContentType(context, spWeb, contentType);
            CreateSiteField(context, spWeb, contentType);
            AddContentType(context, spWeb);

            Console.WriteLine("Success");
            Console.ReadLine();
        }

    }
    private static ContentType CreateSpContentType(ClientContext context, Web spWeb, ContentType contentType)
    {

        try
        {
        contentType= spWeb.ContentTypes.Add(new ContentTypeCreationInformation
            {
                Name = "Employee Info",
                Id = "0x0100A33D9AD9805788419BDAAC2CCB37509E",
                Group = "List Content Types"
            });           
            context.ExecuteQuery();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        return contentType;
    }
    private static void CreateSiteField(ClientContext context, Web spWeb ,ContentType contentType)
    {
        #region[Variables]
        string[] trgtfld = { "EmployeeName", "EmpAddress", "EmpCity", "JoinDate", "EmpGender" };
        FieldCollection fields = null;
        FieldLinkCreationInformation fldLink = null;
        Field txtFld = null;
        string TxtFieldAsXML = string.Empty;
        Field addFld = null;
        string addFieldAsXML = string.Empty;
        string cityFieldAsXML = string.Empty;
        Field cityFld = null;
        string jdFieldAsXML = string.Empty;
        Field jdFld = null;
        string genFieldAsXML = string.Empty;
        Field genFld = null;
        #endregion

        try
        {
            fields = spWeb.Fields;
            context.Load(fields);               
            //Adding site column to site 
            TxtFieldAsXML = @"<Field Name='EmployeeName' DisplayName='Employee Name' Type='Text' Hidden='False' Group='EmployeeData' />";
            txtFld = fields.AddFieldAsXml(TxtFieldAsXML, true, AddFieldOptions.DefaultValue);

            addFieldAsXML = @"<Field Name='EmpAddress' DisplayName='EmpAddress' Type='Note' Hidden='False' Group='EmployeeData' />";
            addFld = fields.AddFieldAsXml(addFieldAsXML, true, AddFieldOptions.DefaultValue);

            cityFieldAsXML = @"<Field Name='EmpCity' DisplayName='EmpCity' Type='Text' Hidden='False' Group='EmployeeData' />";
            cityFld = fields.AddFieldAsXml(cityFieldAsXML, true, AddFieldOptions.DefaultValue);

            jdFieldAsXML = @"<Field Name='JoinDate' DisplayName='JoinDate' Type='DateTime' Hidden='False' Group='EmployeeData' />";
            jdFld = fields.AddFieldAsXml(jdFieldAsXML, true, AddFieldOptions.DefaultValue);

            genFieldAsXML = @"<Field Name='EmpGender' DisplayName='EmpGender' Type='Choice' Hidden='False' Group='EmployeeData' Format='Dropdown'>"
                + "<CHOICES>"
                + "<CHOICE>Male</CHOICE>"
                + "<CHOICE>Female</CHOICE>"
                + "</CHOICES>"
                + "</Field>";
            genFld = fields.AddFieldAsXml(genFieldAsXML, true, AddFieldOptions.DefaultValue);
            context.Load(fields);
            foreach (var fld in trgtfld)
            {
                try
                {
                    contentType = spWeb.ContentTypes.GetById("0x0100A33D9AD9805788419BDAAC2CCB37509E");
                    fldLink = new FieldLinkCreationInformation();
                    fldLink.Field = context.Web.AvailableFields.GetByInternalNameOrTitle(fld);
                    contentType.FieldLinks.Add(fldLink);
                    contentType.Update(false);

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                context.ExecuteQuery();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    private static void AddContentType(ClientContext context, Web spWeb)
    {
        #region[Variables]
        ListCollection spListColl = null;
        ContentType spContentType = null;
        #endregion
try
        {
            spListColl = spWeb.Lists;
            context.Load(spListColl);
            context.ExecuteQuery();
            foreach (List list in spListColl)
            {
                try
                {
                     if (list.BaseTemplate == 100)
                     {
                         list.ContentTypesEnabled = true;
                         spContentType = spWeb.ContentTypes.GetById("0x0100A33D9AD9805788419BDAAC2CCB37509E");
                         list.ContentTypes.AddExistingContentType(spContentType);
                         list.Update();
                         spWeb.Update();
                         context.ExecuteQuery();
                      }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

After running the code, we can check the content type in Site content type option under site setting. Then clicking on the content type title (Employee Info), we can check the field of content type. Please refer to the below image for better reference.

Img: Content type created

Img: Field of Content type created

Keywords:
1. Create List Content type and add it to all custom lists present in the site using CSOM
2. How to create List content type and its field using CSOM
3. How to add content type and its field to a List using CSOM

Author: Softree Technology

Leave a Reply