SharePoint - Client Side Object Model(CSOM) - Managed - Add Fields to an Existing List

Problem Definition

Add Fields to Existing List using Managed Code and Client Side Object Model(CSOM) for SharePoint 2013.

Prerequisites

Code Example




 /// <summary>
 /// Add fields to an existing list
 /// </summary>
 /// <param name="title"></param>
 /// <param name="fieldsWithTypes">Pass if Comma Separated combination of field and type and separate the combo with a semicolon
 /// Eg: "FirstName,Text;Created,Date"
 /// </param>
 public static void AddFieldsToExistingList(string title, string fieldsWithTypes)
 {
            try
            {
                //var spContext = new ClientContext("http://<your server>/<site>/");
                using (spContext)
                {
                    // Client side SP Web Conext
                    var web = spContext.Web;
                    // Define Exception scope for the site context.
                    var exScope = new ExceptionHandlingScope(spContext);
                    // Get list by its title
                    List list = web.Lists.GetByTitle(title);
                    // Get list's field Collection
                    FieldCollection collField = list.Fields;
                    // Parse new fields to be added
                    var fieldsDict = fieldsWithTypes.Split(';').ToList().ToDictionary(x => x.Split(',')[0], x => x.Split(',')[1]);
                    // Loop through list of fields
                    foreach (var field in fieldsDict)
                    {
                        // Use XML syntaxt and define the field to be added
                        string fieldSchema = $"<Field Type='{field.Value}' DisplayName='{field.Key}' Name='{field.Key}' />";
                        // Add Field to the collection of fields(MSDN)
                        // 1# Argument: stringXML - field's xml
                        // 2# Argument: addToDefaultView - sent to try if you want to add it to the default view.
                        // 3# Argument: AddFieldOprions:
                        // DefaultValue - Enumeration whose values specify that a new field added to the list must also be 
                        //                added to the default content type in the site collection.The value = 0.
                        // AddToDefaultContentType - Enumeration whose values specify that a new field added to the list 
                        //                must also be added to the default content type in the site collection.The value = 1.
                        // AddToNoContentType - Enumeration whose values specify that a new field must not be added to any other 
                        //                      content type.The value = 2.
                        // AddToAllContentTypes  - Enumeration whose values specify that a new field that is added to the specified list 
                        //                         must also be added to all content types in the site collection.The value = 4.
                        // AddFieldInternalNameHint  - Enumeration whose values specify adding an internal field name hint for the purpose 
                        //                              of avoiding possible database locking or field renaming operations.The value = 8.
                        // AddFieldToDefaultView  - Enumeration whose values specify that a new field that is added to the specified list 
                        //                          must also be added to the default list view.The value = 16.
                        // AddFieldCheckDisplayName  -  Enumeration whose values specify to confirm that no other field has the same display name. The value = 32
                        collField.AddFieldAsXml(fieldSchema, true, AddFieldOptions.AddToDefaultContentType);
                    }
                    //Load so Context's with fields
                    spContext.Load(collField);
                    // Execute the query to finalize your add
                    spContext.ExecuteQuery();
                    // Print the list fields
                    Console.WriteLine($"Added  new fields to {title} list:\r\n");
                    foreach (Field field in collField)
                        Console.WriteLine(field.Title);
                }
            }
            catch (Exception ex)
            {
                // Print error message
                Console.WriteLine(ex.ToString());
            }
 }


Code Result






Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)