In Focus

SharePoint Basic Site Field Operations Using TypeScript

In this article, you will learn how to perform SharePoint basic site field or column operations, using TypeScript, with an Object Oriented approach.

Introduction
 
In this article, you will learn how to perform basic site field operations (site scoped columns) on SharePoint site collections, using TypeScript, with the help of classes and variables. You will see how to create, retrieve, update, and delete the site fields with the help of  an Object Oriented approach.
 
To learn about TypeScript basics and for the prerequisites to be available on Visual Studio for SharePoint TypeScript programming, you can refer to the following article.
In my other article, I have explained about implementing TypeScript basic examples in SharePoint Visual Studio projects.
 This article focuses more on implementing the site column operations using ECMA script, with the help of TypeScript and Object Oriented programming concepts.
 
 Class
 
The class holds the necessary members. This means, the class will hold the necessary variables, constructors, and the defined functions.
  
Variables
 
The necessary variables, common for all the functions, are defined as the member variables. In this case, all the variables to be defined in the base class are given below.
  1. // Variables or Objects  
  2. public context: SP.ClientContext;  
  3. public site: SP.Site;  
  4. public web: SP.Web;  
  5. public fields: SP.FieldCollection;  
Constructor
 
The constructor can be defined with no parameters or with parameters, depending on the requirement. The context of the site can be set using the respective method. With the help of context object, the other variables can be set using the respective methods. The variables/objects set using the constructor are context, site, root web and fields collection.
  1. // Set objects  
  2. constructor() {  
  3.     this.context = new SP.ClientContext();  
  4.     this.site = this.context.get_site();  
  5.     this.web = this.site.get_rootWeb();  
  6.     this.fields = this.web.get_fields();  
  7. }  
Functions
 
The required functions are defined inside the class. In this sample, the basic field operations mentioned below are defined using the functions.
  1. Retrieve Fields
    The fields available in the site collection are retrieved. The field collection is retrieved with the help of context and root web object. The field collection object query needs to be loaded and executed using the context to get the results.

  2. Retrieve Field
    The field from the root object is retrieved using the field title or name. After retrieving all the fields using the above operation, the particular field is accessed using the getbytitle method. Then the query will be executed. The input parameter is field title.

  3. Create Field
    The field can be created on the site collection with the help of field XML and necessary content type information. The below sample shows creating a text field.

  4. Delete Field
    The field to be deleted needs to be retrieved using the above retrieval operation. Then the field object is deleted using the delete method before executing the query.
 The collection/objects need to be loaded and executed for all the operations, using the context object (defined in the constructor). The code snippet, mentioned below shows the functions defined inside the class.
  1. class SPFieldOperations {  
  2.     // Variables or Objects  
  3.     public context: SP.ClientContext;  
  4.     public site: SP.Site;  
  5.     public web: SP.Web;  
  6.     public fields: SP.FieldCollection;  
  7.   
  8.     // Set objects  
  9.     constructor() {  
  10.         this.context = new SP.ClientContext();  
  11.         this.site = this.context.get_site();  
  12.         this.web = this.site.get_rootWeb();  
  13.         this.fields = this.web.get_fields();  
  14.     }  
  15.   
  16.     // Retrieves all fields from site collection  
  17.     public GetFields() {  
  18.         let availFields = this.fields;  
  19.         this.context.load(availFields);  
  20.         this.context.executeQueryAsync(  
  21.             function () {  
  22.                 let siteColumns = availFields.getEnumerator();  
  23.                 while (siteColumns.moveNext()) {  
  24.                     let siteColumn = siteColumns.get_current();  
  25.                     console.log(siteColumn.get_title());  
  26.                 }  
  27.             },  
  28.             function (sender, args) {  
  29.                 console.log(args.get_message());  
  30.             }  
  31.         );  
  32.     }  
  33.   
  34.     // Retrieves particular field  
  35.     public GetField() {  
  36.         let availField = this.fields.getByTitle("Title");  
  37.         this.context.load(availField);  
  38.         this.context.executeQueryAsync(  
  39.             function () {  
  40.                 console.log(availField.get_id());  
  41.                 console.log(availField.get_description());  
  42.                 console.log(availField.get_defaultValue());  
  43.                 console.log(availField.get_group());  
  44.                 console.log(availField.get_scope());  
  45.             },  
  46.             function (sender, args) {  
  47.                 console.log(args.get_message());  
  48.             }  
  49.         );  
  50.     }  
  51.   
  52.     // Creates a field  
  53.     public CreateField() {  
  54.         let newField = this.context.castTo(this.fields.addFieldAsXml('<Field Type="Text" DisplayName="CustomColumn1" Name="CustomColumn1" />',  
  55.                 true, SP.AddFieldOptions.addToDefaultContentType),  
  56.             SP.FieldText);  
  57.         this.context.load(newField);  
  58.         this.context.executeQueryAsync(  
  59.             function () {  
  60.                 console.log("Column Created");  
  61.             },  
  62.             function (sender, args) {  
  63.                 console.log(args.get_message());  
  64.             }  
  65.         );  
  66.     }  
  67.   
  68.     // Deletes a field  
  69.     public DeleteField() {  
  70.         let existingColumn = this.fields.getByTitle("CustomColumn1");  
  71.         existingColumn.deleteObject();  
  72.         this.context.executeQueryAsync(  
  73.             function () {  
  74.                 console.log("Column Deleted");  
  75.             },  
  76.             function (sender, args) {  
  77.                 console.log(args.get_message());  
  78.             }  
  79.         );  
  80.     }  
  81. }  
 Execution
 
The classes are instantiated with the help of objects. Context of the site is set using the constructors. The code snippet, mentioned below, triggers the members defined inside the classes. The comments are provided along with the function calls, to explain every step in detail.
  1. // Loads necessary files  
  2. $(document).ready(function () {  
  3.     SP.SOD.executeOrDelayUntilScriptLoaded(function () {  
  4.         SP.SOD.executeOrDelayUntilScriptLoaded(() => GetData(), 'SP.js');  
  5.     }, 'SP.RunTime.js');  
  6.   
  7. });  
  8.   
  9. // Instantiate object and call the methods  
  10. function GetData() {  
  11.     let fieldsOps = new SPFieldOperations();  
  12.     // Uncomment necessary operations  
  13.     //fieldsOps.GetFields(); // Retrieves single field  
  14.     //fieldsOps.GetField(); // Retrieves required field  
  15.     //fieldsOps.CreateField(); // Creates a field  
  16.     //fieldsOps.DeleteField(); // Deletes a field  
  17. }  
Summary
 
Thus, you have learned about creating, retrieving, or deleting the fields or columns on the site collection using TypeScript with an Object Oriented approach.