Add site column to content type using CSOM
Add site column to content type using CSOM programmatically in SharePoint
Add site column to content type using CSOM. In this post, I describe you to add the site column to the content type using csom. If you want to create content type programmatically using csom, I discussed in my previous post. Create Content Type using CSOM. Also, I will describe you to create site column using csom in my next post. Below is complete code.[AdSense-A]
public static void AddColumnINContenType(string ColumnName, string siteurls, string contentTypeName) { try { ClientContext clientContext = new ClientContext(siteurls); Web rootWeb = clientContext.Site.RootWeb; Field session = rootWeb.Fields.GetByInternalNameOrTitle(ColumnName); var contentType = GetContentTypeByName(clientContext, rootWeb, contentTypeName); if (contentType == null) return; // content type was not found clientContext.Load(contentType.FieldLinks, c => c.IncludeWithDefaultProperties(pr => pr.Id)); clientContext.Load(contentType.Fields, c => c.IncludeWithDefaultProperties(pr => pr.Id)); clientContext.ExecuteQuery(); // ContentType sessionContentType = rootWeb.ContentTypes.GetById("0x0100BDD5E43587AF469CA722FD068065DF5D"); clientContext.Load(session); clientContext.ExecuteQuery(); var hasFieldConnectedTitle = contentType.FieldLinks.Any(f => f.Name == "Title"); if (hasFieldConnectedTitle) { var fieldLinks = contentType.FieldLinks; //Field hasFieldConnected11 = contentType.Fields.GetByTitle("Title"); Field hasFieldConnected11 = rootWeb.Fields.GetByInternalNameOrTitle("Title"); clientContext.Load(hasFieldConnected11); clientContext.ExecuteQuery(); var fieldLinkToRemove = fieldLinks.GetById(hasFieldConnected11.Id); fieldLinkToRemove.DeleteObject(); contentType.Update(true); //push changes clientContext.ExecuteQuery(); } // Determine whether the content type refers to the field. var hasFieldConnected = contentType.FieldLinks.Any(f => f.Name == ColumnName); if (hasFieldConnected) return; contentType.FieldLinks.Add(new FieldLinkCreationInformation { Field = session }); contentType.Update(true); clientContext.ExecuteQuery(); } catch (Exception ex) { } }
Nice Post Thanx