Tuesday, July 16, 2019

CRUD Operations Using SPServices (Create Operation)

SPServices is a jQuery library which abstracts SharePoint’s Web Services and makes them easier to use. It also includes functions which use the various Web Service operations to provide more useful capabilities. It works entirely client side and requires no server install. SPServices can be used with SharePoint 2007, 2010, and 2013, whether on premises or hosted with Office365 or others. SPServices is primarily hosted on Codeplex, with this repository mirroring most of the downloads there. With Codeplex shutting down, any new activity will happen on the NEW Github-backed site. Check out the newer location (http://sympmarc.github.io/SPServices/) for SPServices information on Github pages. We can perform Create, Read, Update, Delete operations easily using SPServices. Let us go through one by one.
In my earlier post, we have discussed about Read Operation. Now, we will discuss about Create operation.


Basic Preparations

List Creation

We have created a custom list name "EmployeeMaster" in Sharepoint having Columns "Title", "First Name", "Last Name", "Employee ID", "Date of Joining".



Now on page we have added references of jquery and spservices files.


<script type="text/javascript" src="../Scripts/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="../Scripts/jquery.SPServices-2014.02.min.js"></script>


Next, we have added some CSS.

<style type="text/css">
 table thead th,
 table tbody tr td
 {
  border:thin gray dotted;
 }
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">



1. CREATE (Add record to list)
For this, first we create a page having 5 boxes for input the value and a button to submit the data.

The HTML code is as below.

<div>
 <table>
  <tr>
   <td>
    Title
   </td>
   <td>
    <input type="text" id="txtTitle" title="Title">
   </td>
  </tr>
  <tr>
   <td>
    First Name
   </td>
   <td>
    <input type="text" id="txtFirstName" title="First Name">
   </td>
  </tr>
  <tr>
   <td>
    Last Name
   </td>
   <td>
    <input type="text" id="txtLastName" title="Last Name">
   </td>
  </tr>
  <tr>
   <td>
    Employee ID
   </td>
   <td>
    <input type="text" id="txtEmployeeID" title="Employee ID">
   </td>
  </tr>
  <tr>
   <td>
    Date of Joining
   </td>
   <td>
    <input type="text" id="txtDOJ" title="Date of Joining">
   </td>
  </tr>
  <tr>
   <td colspan="2" align="center">
    <input type="button" id="btnSubmit" title="Submit" value="Submit" onclick="AddRecord();">
   </td>
  </tr>
 </table> 
</div> 

Image View:-



Now add code for submitting the data to list as below.


<script type="text/javascript">
 function AddRecord()
 {
  var vrTitle = $('#txtTitle').val();
  var vrFirstName = $('#txtFirstName').val();
  var vrLastName = $('#txtLastName').val();
  var vrEmployeeID = $('#txtEmployeeID').val();
  var vrDOJ = formatDate(new Date($('#txtDOJ').val()));

  $().SPServices(
  {
   operation: "UpdateListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   batchCmd: "New",
   listName: "EmployeeMaster",
   valuepairs: [
       ["Title", vrTitle],
       ["First_x0020_Name", vrFirstName],
       ["Last_x0020_Name", vrLastName],
       ["Employee_x0020_ID", vrEmployeeID],
       ["Date_x0020_Of_x0020_Joining", vrDOJ]
      ],

   completefunc: function (xData, Status)
   {
    if(Status == "success")
    {
     alert("Record Added Successfully");
     GetRecords();
    }
    else
    {
     alert("Error");
    }
   }
  });
 }
 
 function formatDate(date)
 {
  var d = new Date(date),
  month = '' + (d.getMonth() + 1),
  day = '' + d.getDate(),
  year = d.getFullYear();
  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;
  return [year, month, day].join('-');
 }
</script>


Now add below script to make Date Of Joining box as DatePicker control.

<script type="text/javascript">
 $(document).ready(function()
 {
  $("#txtDOJ").datepicker();
 });
</script>

Lastly, add function to get records from list after saving the data.


<script type="text/javascript">
 function GetRecords()
 {
  $().SPServices(
  {
   operation: "GetListItems",
   webURL: $(this).attr('location').origin,
   async: false,
   listName: "EmployeeMaster",
   CAMLQuery: "<Query>" +
       "<Where>" +
        "<Gt>" +
         "<FieldRef Name=\"Date_x0020_Of_x0020_Joining\" />" +
         "<Value IncludeTimeValue=\"TRUE\" Type=\"DateTime\">2014-01-01</Value>" +
        "</Gt>" +
       "</Where>" +
      "</Query>",
   CAMLViewFields: "<ViewFields>" +
        "<FieldRef Name=\"Employee_x0020_ID\" />" +
        "<FieldRef Name=\"First_x0020_Name\" />" +
        "<FieldRef Name=\"Last_x0020_Name\" />" +
        "<FieldRef Name=\"Date_x0020_Of_x0020_Joining\" />" +
       "</ViewFields>",
   completefunc: function (xData, Status)
   {
    if(Status == 'success')
    {
     var vrTableHTML = '';

     vrTableHTML += '<thead>' + 
          '<th>' + 'First Name' + '</th>' + 
          '<th>' + 'Last Name' + '</th>' + 
          '<th>' + 'Employee ID' + '</th>' + 
          '<th>' + 'Date Of Joining' + '</th>' + 
         '</thead>';

     vrTableHTML += '<tbody>';
     $(xData.responseXML).SPFilterNode("z:row").each(function()
     {
      vrTableHTML += '<tr>' + 
           '<td>' + $(this).attr("ows_First_x0020_Name") + '</td>' + 
           '<td>' + $(this).attr("ows_Last_x0020_Name") + '</td>' + 
           '<td>' + $(this).attr("ows_Employee_x0020_ID") + '</td>' + 
           '<td>' + ($(this).attr("ows_Date_x0020_Of_x0020_Joining")).split(' ')[0] + '</td>' + 
          '</tr>';
     });
     vrTableHTML += '</tbody>';
     $('#tblResult').html(vrTableHTML);
     $('#dvResult').show();
    }
    else
    {
    }
   }
  });
 }
</script>

Now start filling the data.
Below are two images-
1. All fields except Date of Joining

2. Date of Joining




Now click on Submit button. If everything goes fine, record will be added to list and a message will be prompted on screen.



Now check the list. If the inserted record is available there.

This way, we can add records to SharePoint list using client side code.








No comments:

Post a Comment

Note: Only a member of this blog may post a comment.