Thursday, August 13, 2015

Read & Update Display Names of List Columns through Javascript in Sharepoint

We can Read Columns (Internal Name, Display Name / Title, Type etc) & also Update Columns (Display Name / Title) of a List in Sharepoint ( 2010 & above ) using Client Object Model.

Below is the sample code in javascript to read Columns for a List.
 function retrieveAllFieldsOfList(listName) {  
   var ctx = SP.ClientContext.get_current();  
      var web = ctx.get_web();  
      var list = web.get_lists().getByTitle(listName);  
      var fields = list.get_fields();  
      ctx.load(fields, 'Include(Title,InternalName)');  
      ctx.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.Failure));  
 }  
 function Success()  
 {            
      var _fields = '';  
      var lEnum = fields.getEnumerator();  
      while(lEnum.moveNext())  
      {  
           var internalName = lEnum.get_current().get_internalName();   
           var title = lEnum.get_current().get_title();  
           _fields = _fields + 'Internal Name:' +internalName+ ',Title:' +title+ ';';  
      }  
      console.log(_fields);  
 }  
 function Failure(sender, args)  
 {  
      console.log("Failed" + args.get_message());  
 }  

Below is the Sample Code in javascript to Update Title / Display Name of a Field in a Sharepoint List
 function updateMonths(listName){  
      var ctx = SP.ClientContext.get_current();  
      var web = ctx.get_web();  
      var list = web.get_lists().getByTitle(listName);  
      //Below field section to be repeated for multiple field updates  
      var field = list.get_fields().getByInternalNameOrTitle('<Internal Name / Existing Title>');  
      field.set_title('<New Title>');  
      field.update();  
      ctx.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.Failure));  
 }  
 function Success()  
 {            
      console.log('Updated Successfully.');  
 }  
 function Failure(sender, args)  
 {  
      console.log("Failed" + args.get_message());  
 }  

No comments:

Post a Comment