Tuesday, June 24, 2014

Create Lookup Site Column using Javascript object model in SharePoint 2013 / 2010

Sometimes we need to create a lookup column as a site column to use it in different list or use it in a content type. Below is a simple code to create a Lookup site column using javascript object model. The code works in both SharePoint 2010 and SharePoint 2013 environment.


 jQuery(function($) {   
        CreateSiteLookupColumn();   
 });   
      var clientContext;  
      var oWebSite;  
      var oList;  
      function CreateSiteLookupColumn()  
      {  
         clientContext= new SP.ClientContext.get_current();   
         oWebSite= clientContext.get_web();  
         //Lookup List  
         oList=oWebSite.get_lists().getByTitle('Countries');  
         clientContext.load(oList);  
         clientContext.load(oWebSite);  
         clientContext.executeQueryAsync(function () {  
                 var fieldXml="<Field Name='Country' DisplayName='Country' Type='Lookup' Required='FALSE' Group='Operations'/>";  
                 var lookupField=oWebSite.get_fields().addFieldAsXml(fieldXml,true,SP.AddFieldOptions.addFieldCheckDisplayName);  
                //Cast to Lookup field to set List Name and lookup column       
                 var fieldLookup = clientContext.castTo(lookupField, SP.FieldLookup);  
                 fieldLookup.set_lookupList(oList.get_id());  
                 fieldLookup.set_lookupField("Title");  
                 fieldLookup.update();              
                 clientContext.executeQueryAsync(function () {   
                         alert('Field Added');   
                      }, function (sender, args) {   
                            alert(args.get_message() + '\n' + args.get_stackTrace());   
                      });   
         },function (sender, args) {   
          alert(args.get_message() + '\n' + args.get_stackTrace());   
      });     
 }  

No comments:

Post a Comment