Sunday, October 14, 2012

Creating a List in SharePoint using ECMA Script

In this post, I will explain how to create a list in SharePoint using ECMA script. Use the ListCreationInformation object to define list properties and then pass this object to add (listCreationinformation object).
<script type="text/ecmascript">
function createSPList()
{
  var clientContext = new SP.ClientContext.get_current();
  var oWeb=clientContext.get_web();
  var listCreation = new SP.ListCreationInformation();
  listCreation.set_title('My Custom List');
  listCreation.set_templateType(SP.ListTemplateType.genericList);
  listCreation.set_description('List created using ECMA Script');

  this.oList = oWeb.get_lists().add(listCreation);
  clientContext.load(oList);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,this.OnFailure));
  }

function OnSuccess()
{
 alert(oList.get_title() + ' created.');
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  }
 </script>

Refer the below link for list template type

Deleting a List Item in SharePoint list using ECMA Script

In this post, I will explain how to delete list item in SharePoint list using ECMA script. To delete list item, firstly use getItemById (ID) function to fetch item to be deleted and then call deleteObject () to delete list item.
<script type="text/ecmascript">
function DisplayListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  this.oListItem = oList.getItemById(3);
  oListItem.deleteObject();  
  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this, this.OnFailure));
  }
function OnSuccess()
{
 alert('Item deleted successfully');  
 }
function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +  args.get_stackTrace());
  }

</script>

Sunday, October 7, 2012

Updating a list item in SharePoint list using ECMA Script

In this post I will explain how to update list item in SharePoint list using ECMA script. To update list items, firstly use getItemById (ID) function to fetch item to be updated and then set value for that item. Finally call update () function to update list.

Add the below code in content editor web part and see the result

<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(UpdateListItems, "sp.js");

function UpdateListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
  this.oListItem = oList.getItemById(2);
       
    oListItem.set_item('Title', 'Somnath');
    oListItem.set_item('LastName', 'Matere');
    oListItem.set_item('WorkingUnit', 'IT');
       
    oListItem.update();

    clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate
(this,this.OnSuccess), Function.createDelegate(this,       this.OnFailure));
  }

function OnSuccess()
{
 alert('Item Updated successfully');
  
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Adding a list item in SharePoint list using ECMA Script

In this post I will explain how to create/add list item in SharePoint list using ECMA script. To create list items, firstly create a ListItemCreationInformation object, set its properties and pass it as parameter to the addItem(parameter) function of the list object. Then set the properties on the list item and finally call update() function to update list.

Add the below code in content editor web part and see the result
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(AddListItems, "sp.js");

function AddListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
  var listItemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(listItemCreateInfo);
       
    oListItem.set_item('Title', 'Somnath');
    oListItem.set_item('LastName', 'Matere');
    oListItem.set_item('WorkingUnit', 'IT');
       
    oListItem.update();

    clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{
 alert('Item Added successfully');
  
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Retrieve SharePoint List Items Using ECMA Script Part 2

As explained in previous post I will show how to retrieve list items using getItems (query). Here we will use the same SharePoint list specified in previous post. We will replace ECMA Script code specified in the Content Editor Web part.
getItems (query) function enables us to define CAML query that specifies which items to return or we can use the set_viewXml function to define query and return items that meet specific criteria.
Approach 1:
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");

function RetrieveListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  var CAMLquery = SP.CamlQuery.createAllItemsQuery();
  this.oAllListItem = oList.getItems(CAMLquery);
  //clientContext.load(this.oAllListItem);
clientContext.load(this.oAllListItem,'Include(Id,Title, LastName,WorkingUnit)');
  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{

    var Html ='';
    var ListEnumerator = this.oAllListItem.getEnumerator();
Html='<table cellspacing="3" cellpadding="3" border="0"><tr><td>ID</td><td> First Name</td><td> Last Name</td><td> Department</td></tr>';
    while(ListEnumerator.moveNext())
    {
                var oItem = ListEnumerator.get_current();
                var ID= oItem.get_id();
var title=oItem.get_item('Title');
var lastName=oItem.get_item('LastName');
var dept=oItem.get_item('WorkingUnit');
   
   Html += '<tr><td>'+ID+'</td><td>'+title+'</td><td>'+lastName+'</td><td>'+
                    dept+'</td></tr></table>';
  
   }

   document.getElementById('ECMADiv').innerHTML =Html;
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Approach 2:
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");

function RetrieveListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  var camlQuery = new SP.CamlQuery();
  camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>2</Value></Geq></Where></Query><RowLimit>2</RowLimit></View>');
 
  this.oAllListItem = oList.getItems(camlQuery);
  clientContext.load(this.oAllListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{

    var Html ='';

    var ListEnumerator = this.oAllListItem.getEnumerator();
Html='<table cellspacing="3" cellpadding="3" border="0"><tr><td>ID</td><td> First Name</td><td> Last Name</td><td> Department</td></tr>';
    while(ListEnumerator.moveNext())
    {
                var oItem = ListEnumerator.get_current();
                var ID= oItem.get_id();
                var title=oItem.get_item('Title');
                var lastName=oItem.get_item('LastName');
                var dept=oItem.get_item('WorkingUnit');
   
   Html += '<tr><td>'+ID+'</td><td>'+title+'</td><td>'+lastName+'</td><td>'+
                    dept+'</td></tr></table>';

  
   }

   document.getElementById('ECMADiv').innerHTML =Html;
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Retrieve SharePoint List Items Using ECMA Script Part 1

In this post I will explain how to retrieve SharePoint list items using Client OM. To get items from a list using ECMA Script we can use below two functions
1.       getItemsById (id) - return a single item.
2.       getItems(query)- return multiple items
In this post we will retrieve list items using getItemsById () function.
Step 1: Create a custom list and name it as Employees.
Step 2: Rename Title column as FirstName, Add LastName, and WorkingUnit columns.
Step 3: Add content editor web part and add the below code
<script type="text/ecmascript">
ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");

function RetrieveListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
  this.oListItem = oList.getItemById(1);
  clientContext.load(this.oListItem);
  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,       this.OnFailure));
  }

function OnSuccess()
{
    var listItemInfo ='';
    var Html ='';

   Html += '<table cellspacing="'+3+'" cellpadding="'+3+'" border="'+0+'"><tr><td>ID</td><td>First Name</td><td>Last Name</td><td>Department</td></tr>'+
                    '<tr><td>'+oListItem.get_id()+'</td><td>'+oListItem.get_item('Title')+'</td><td>'+oListItem.get_item('LastName')+'</td><td>'+
                    oListItem.get_item('WorkingUnit')+'</td></tr></table>';
   
 document.getElementById('ECMADiv').innerHTML =Html;
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

Step 4: Add HTML Form web part and add below code
<table cellspacing="3" cellpadding="3" border="2">
<tbody><tr><td style="background-color:#f9f9f9"><div>
<div id="ECMADiv"></div>
</div></td>
</tr>
</tbody></table>
 In next post I will explain how to retrieve list items using getItems().

Tuesday, October 2, 2012

Get query string value using ECMA script

In this post, I will explain how to get query string value using ECMA script

<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(GetValue, "sp.js");

function GetValue()
  {
   var qs = getQueryStringValue();
   var myParam= qs["ID"];
   alert(myParam);  
  }

 function getQueryStringValue()
  {
      var associate  = {};
      var decodevalue = function (s)
      {
        return decodeURIComponent(s.replace(/\+/g, " "));
       };
      var queryString = location.search.substring(1);    
      var keyValues = queryString.split('&');
      for(var sm in keyValues)
      {  
       var key = keyValues[sm].split('=');    
       if (key.length > 1)
        { 
          associate[decodevalue(key[0])] = decodevalue(key[1]); 
         } 
      }   
     return associate; 
   } 
  
</script>

Get all subsites under SharePoint site using ECMA script

In this post, I will explain how to get all subsites under SharePoint site using ECMA script

<script type="text/ecmascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(GetSites, "sp.js");
function GetSites()
{
currentcontext = new SP.ClientContext.get_current();
if(currentcontext!=null && currentcontext!=undefined ){
currentweb = currentcontext.get_web();
this.subsites = currentweb.get_webs();
currentcontext.load(this.subsites);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.OnSuccess),
Function.createDelegate(this, this.OnFailure));
}
}
function OnSuccess(sender, args) {
var subsite = '';
var Listsubsite= this.subsites.getEnumerator();
while (Listsubsite.moveNext())
{
var Site = Listsubsite.get_current();
subsite += '\nID: ' + Site.get_id() + '\nTitle: ' + Site.get_title()+'\n Created date:'+ Site.get_created();
}
alert(subsite);
}
function OnFailure(sender, args) {
alert('Error');
}
</script>

Get Top site collection using ECMA script

In this post, I will explain how to get top site collection using ECMA script

 <script type="text/ecmascript">
var currentcontext = null;
var currentsitecol = null;
ExecuteOrDelayUntilScriptLoaded(GetTopLevelSiteCollection, "sp.js");
function GetTopLevelSiteCollection()
{
currentcontext = new SP.ClientContext.get_current();
if(currentcontext!=null && currentcontext!=undefined ){
currentsitecol= currentcontext.get_site().get_rootWeb();
currentcontext.load(currentsitecol);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.OnSuccess),
Function.createDelegate(this, this.OnFailure));
}
}
function OnSuccess(sender, args) {
var sitecol='';
sitecol+= '\nID: ' + currentsitecol.get_id() + '\nTitle: ' + currentsitecol.get_title()+'\n Created date:'+ currentsitecol.get_created();
alert(sitecol);
}
function OnFailure(sender, args) {
alert('Error');
}
</script>