Introduction

In this article, we will learn how to insert a record into the SharePoint custom list having a lookup column. In this example, first, we will create the Department List and then create the Employee list with lookup column having column name DeptName. We also cover how to upload pictures in the picture library and how to make a relation between Employee list (Custom List) and EmployeePicture (Picture Library). We will also cover the jquery DataTable concept. Using Jquery DataTable we will display the list of records available in Employee (Custome list). We will also perform the Delete operation using Rest API, on click of the delete of delete hyperlink a confirmation popup message will be displayed. Depending on the conformation we will delete the record and rebind the list of the item available in the Employee list (Custom List )
A Lookup field is a field type that allows you to connect a custom list to a field from another custom list. In this article, we refer DeptName field from the Department list (Custom List) as a lookup field. In Employee List we will add one column DeptName as a lookup field from the Department list.
In the case of Picture Library first, we will insert a record into EmployeeList. In EmployeeList having one column EmpProfilePicture, we will insert EmpProfilePicture value (EmpName + yyyyMMddhhmmss + picture extension ) and finally upload the picture into the EmployeePicture library with the same name as inserted into Employee List.
After inserting the record into the Employee list we will upload the Employee profile picture into Picture Library (EmployeePicture) and finally display the Employee in Jquery DataTable.

Scenario

In this example, we will create a custom list called "Department" and in the list, we will create a DeptName field. (ID & Title is the default field). Now create the Picture Library list called "EmployeePicture" with the default field and finally create the custom list "Employee" and in this list, we will create an EmpName field (Single line text), Gender field (Multi Selection), EmpDOJ (Date Time), EmpProfilePicture (Single line text), DeptName (lookup field from Department List ), City (Single line text).
In the Employee custom list, we will insert the record and DeptName we will refer from the Department custom list and name of the picture used during the EmployeePicture upload in the picture library.
How To Save Lookup Field Values In SharePoint Using Rest API
Employee List
A column stores information about each item in the list. The following columns are currently available in this list
Column
Type
Title
Single line of text
EmpName
Single line of text
Gender
Choice
EmpDOJ
Date and Time
EmpProfilePicture
Single line of text
DeptName
Lookup
City
Single line of text
Modified
Date and Time
Created
Date and Time
Created By
Person or Group
Modified By
Person or Group
Department List
A column stores information about each item in the list. The following columns are currently available in this list
Column (click to edit)
Type
Title
Single line of text
DeptName
Single line of text
Modified
Date and Time
Created
Date and Time
Created By
Person or Group
Modified By
Person or Group

Implementation

Step 1
Create Department List with the field DeptName, field ID & Title as Default field
How To Save Lookup Field Values In SharePoint Using Rest API
Step 2
Create Employee List with the below field detail. In the Employee list, DeptName is a lookup field and we used EmpProfilePicture name during the picture upload in the Picture library.
How To Save Lookup Field Values In SharePoint Using Rest API
Step 3
Create Picture Library called "EmployeePicture" with the default field name. After the data is inserted into the Employee List we will upload the picture into EmployeePicture library.
How To Save Lookup Field Values In SharePoint Using Rest API
Step 4
Create an HTML form with the below field and finally add two-buttons, the "Insert Employee" and the "Get Employee" button.
On click of the employee button, we will insert the record into the Employee List and upload the picture into the picture library.
On load of the HTML form we will bind the Department dropdown list from the Department List with ID and Value (Text > 'IT', Value > 1).
How To Save Lookup Field Values In SharePoint Using Rest API
Step 5 - HTML code
  1. <html>
  2. <head>
  3. <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  4. <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
  5. <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css" />
  6. <script src="EmployeeApi.js"></script>
  7. </head>
  8. <body>
  9. <div>
  10. <table>
  11. <tr>
  12. <td>Title</td>
  13. <td>
  14. <input type="Text" id="txtTitle" value="Mr">
  15. </td>
  16. </tr>
  17. <tr>
  18. <td>
  19. EmpName
  20. </td>
  21. <td>
  22. <input type="Text" id="txtEmpName" value="Ronado">
  23. </td>
  24. </tr>
  25. <tr>
  26. <td>
  27. Gender
  28. </td>
  29. <td>
  30. <input type="radio" id="male" name="gender" value="male">
  31. <label for="male">Male</label>
  32. <input type="radio" id="female" name="gender" value="female">
  33. <label for="female">Female</label>
  34. </td>
  35. </tr>
  36. <tr>
  37. <td>
  38. EmpDOJ
  39. </td>
  40. <td>
  41. <input type="Text" id="txtEmpDOJ" value="01/01/2021">
  42. </td>
  43. </tr>
  44. <tr>
  45. <td>
  46. Select Deparment
  47. </td>
  48. <td>
  49. <select id="ddlDepartment" >
  50. <option value="0">Select</option>
  51. </select>
  52. </td>
  53. </tr>
  54. <tr>
  55. <td>Upload File</td>
  56. <td>
  57. <input type="file" id="getFile" />
  58. </td>
  59. </tr>
  60. <tr>
  61. <td colspan="2">
  62. <input type="button" id="btnInsertEmp" value="Insert Empoyee" />
  63. <input type="button" id="btnSubmitEmp" value="Get Employee" />
  64. <input type="button" value="Upload Profile" id="btnUploadProfile" style="display:none" />
  65. </td>
  66. </tr>
  67. </table>
  68. </div>
  69. <br />
  70. <div id="divResults" style='width:80%'></div>
  71. </body>
  72. </html>
Step 6
Create a JavaScript EmployeeAPI.js
  1. $(document).ready(function () {
  2. $("#btnSubmitEmp").on("click", function () {
  3. $('#example').DataTable();
  4. getEmployeeListData();
  5. $('#example').DataTable();
  6. })
  7. $("#btnInsertEmp").on("click", function () {
  8. debugger;
  9. InsertEmployeeListData();
  10. })
  11. $("#btnUploadProfile").on("click", function () {
  12. debugger;
  13. var files = $("#getFile")[0].files;
  14. uploadFile(files[0]); // uploading singe file
  15. })
  16. addDepartment();
  17. $('#example').DataTable();
  18. });
  19. function ProcessUploadPic() {
  20. if (document.getElementById("fileupload").files.length === 0) {
  21. alert("Select a file!");
  22. return;
  23. }
  24. var parts = document.getElementById("fileupload").value.split("\\");
  25. var filename = parts[parts.length - 1];
  26. var fileInput = document.getElementById("fileupload").files[0];
  27. var picReader = new FileReader();
  28. picReader.addEventListener("load", function (event) {
  29. var picFile = event.target;
  30. var div = document.createElement("div");
  31. div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>";
  32. PerformUploadPic(filename, div)
  33. });
  34. picReader.readAsDataURL(fileInput);
  35. }
  36. function PerformUploadPic(filename, fileData) {
  37. var url = document.URL.split('/');
  38. url = url[0] + "//" + url[2] + "/" + url[3] + "/";
  39. $.ajax({
  40. url: url + "_api/web/getfolderbyserverrelativeurl('EmployeePicture')/files/add(url='" + filename + "', overwrite=true)",
  41. method: "POST",
  42. binaryStringRequestBody: true,
  43. body: fileData,
  44. headers: {
  45. "accept": "application/json; odata=verbose",
  46. "X-RequestDigest": $("#__REQUESTDIGEST").val(),
  47. "content-length": fileData.byteLength
  48. },
  49. success: function (data) {
  50. alert("Success! Your Picture was uploaded to SharePoint.");
  51. },
  52. error: function onQueryErrorAQ(xhr, ajaxOptions, thrownError) {
  53. alert('Error:\n' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
  54. },
  55. state: "Update"
  56. });
  57. }
  58. function uploadFile(uploadFileObj, empProfilePicture) {
  59. debugger;
  60. console.log('Log-1');
  61. var fileName = uploadFileObj.name;
  62. fileName = empProfilePicture+"_" + fileName; // + date.format("ddmmyyyyHHmmss");
  63. var webUrl = _spPageContextInfo.webAbsoluteUrl;
  64. var documentLibrary = "EmployeePicture";
  65. //var folderName = "Folder1";
  66. var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" //+ folderName;
  67. var url = webUrl + "/_api/web/lists/getByTitle(@TargetLibrary)/RootFolder/files/add(url=@TargetFileName,overwrite='true')?" + "@TargetLibrary='" + documentLibrary + "'" + "&@TargetFileName='" + fileName + "'";
  68. debugger;
  69. console.log('Log-2');
  70. uploadFileToFolder(uploadFileObj, url, function (data) {
  71. var file = data.d;
  72. var updateObject = {
  73. __metadata: {
  74. type: file.ListItemAllFields.__metadata.type
  75. },
  76. Name: 'Test Data', //meta data column1
  77. Title: 'Test Data', //meta data column2
  78. };
  79. console.log('Log-3');
  80. debugger;
  81. url = webUrl + "/_api/Web/lists/getbytitle('" + documentLibrary + "')/items(" + file.ListItemAllFields.Id + ")";
  82. url = webUrl + "/_api/Web/lists/getbytitle('" + documentLibrary + "')/items(5)";
  83. updateFileMetadata(url, updateObject, file, function (data) {
  84. debugger;
  85. alert("File uploaded & meta data updation done successfully");
  86. }, function (data) {
  87. debugger;
  88. alert("File upload done but meta data updating FAILED");
  89. });
  90. }, function (data) {
  91. alert("File uploading and meta data updating FAILED");
  92. });
  93. }
  94. function uploadFileToFolder(fileObj, url, success, failure) {
  95. var apiUrl = url;
  96. var getFile = getFileBuffer(fileObj);
  97. debugger;
  98. console.log('Log-2.1');
  99. getFile.done(function (arrayBuffer) {
  100. $.ajax({
  101. url: apiUrl,
  102. type: "POST",
  103. data: arrayBuffer,
  104. processData: false,
  105. async: false,
  106. headers: {
  107. "accept": "application/json;odata=verbose",
  108. "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
  109. },
  110. success: function (data) {
  111. console.log('Log-2.2');
  112. success(data);
  113. },
  114. error: function (data) {
  115. console.log('Log-2.3');
  116. failure(data);
  117. }
  118. });
  119. });
  120. }
  121. function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
  122. $.ajax({
  123. url: apiUrl,
  124. type: "POST",
  125. async: false,
  126. data: JSON.stringify(updateObject),
  127. headers: {
  128. "accept": "application/json;odata=verbose",
  129. "X-RequestDigest": $("#__REQUESTDIGEST").val(),
  130. "Content-Type": "application/json;odata=verbose",
  131. "X-Http-Method": "MERGE",
  132. "IF-MATCH": file.ListItemAllFields.__metadata.etag,
  133. },
  134. success: function (data) {
  135. success(data);
  136. },
  137. error: function (data) {
  138. failure(data);
  139. }
  140. });
  141. }
  142. function getFileBuffer(uploadFile) {
  143. var deferred = jQuery.Deferred();
  144. var reader = new FileReader();
  145. reader.onloadend = function (e) {
  146. deferred.resolve(e.target.result);
  147. }
  148. reader.onerror = function (e) {
  149. deferred.reject(e.target.error);
  150. }
  151. reader.readAsArrayBuffer(uploadFile);
  152. return deferred.promise();
  153. }
  154. function DeleteListItemUsingItemId(Id) {
  155. var check = confirm("Are you sure you want to Delete ?");
  156. if (check == true) {
  157. $.ajax
  158. ({
  159. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employee')/items(" + Id + ")",
  160. type: "POST",
  161. headers:
  162. {
  163. "Accept": "application/json;odata=verbose",
  164. "Content-Type": "application/json;odata=verbose",
  165. "IF-MATCH": "*",
  166. "X-HTTP-Method": "DELETE",
  167. "X-RequestDigest": $("#__REQUESTDIGEST").val()
  168. },
  169. success: function (data, status, xhr) {
  170. console.log("Success");
  171. getEmployeeListData();
  172. },
  173. error: function (xhr, status, error) {
  174. console.log("Failed");
  175. }
  176. });
  177. }
  178. else {
  179. return false;
  180. }
  181. }
  182. function UpdateEmployeeListData(id) {
  183. var title = $("#txtTitle").val();
  184. var EmpName = $("#txtEmpName").val();
  185. var gender = $("input[id='male']:checked").val();
  186. var EmpDOJ = $("#txtEmpDOJ").val();
  187. $.ajax
  188. ({
  189. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items(" + id + ")",
  190. type: "POST",
  191. data: JSON.stringify
  192. ({
  193. __metadata:
  194. {
  195. type: "SP.Data.EmployeeListItem"
  196. },
  197. Title: title,
  198. EmpName: EmpName,
  199. Gender: gender,
  200. EmpDOJ: EmpDOJ,
  201. }),
  202. headers:
  203. {
  204. "Accept": "application/json;odata=verbose",
  205. "Content-Type": "application/json;odata=verbose",
  206. "IF-MATCH": "*",
  207. "X-HTTP-Method": "MERGE",
  208. "X-RequestDigest": $("#__REQUESTDIGEST").val()
  209. },
  210. success: function (data, status, xhr) {
  211. getEmployeeListData();
  212. },
  213. error: function (xhr, status, error) {
  214. $("#ResultDiv").empty().text(xhr.responseJSON.error);
  215. }
  216. });
  217. }
  218. function InsertEmployeeListData() {
  219. var title = $("#txtTitle").val();
  220. var EmpName = $("#txtEmpName").val();
  221. var gender = $("input[id='male']:checked").val();
  222. var EmpDOJ = $("#txtEmpDOJ").val();
  223. var Depid = $("#ddlDepartment").val();
  224. var files = $("#getFile")[0].files;
  225. var date = new Date();
  226. empProfilePicture = EmpName+date.format("ddmmyyyyHHmmss");
  227. $.ajax
  228. ({
  229. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee')/items",
  230. type: "POST",
  231. data: JSON.stringify
  232. ({
  233. __metadata:
  234. {
  235. type: "SP.Data.EmployeeListItem"
  236. },
  237. Title: title,
  238. EmpName: EmpName,
  239. Gender: gender,
  240. EmpDOJ: EmpDOJ,
  241. EmpProfilePicture: empProfilePicture,
  242. DeptNameId: Depid
  243. }),
  244. headers:
  245. {
  246. "Accept": "application/json;odata=verbose",
  247. "Content-Type": "application/json;odata=verbose",
  248. "X-RequestDigest": $("#__REQUESTDIGEST").val()
  249. },
  250. success: function (data, status, xhr) {
  251. uploadFile(files[0], empProfilePicture); // uploading singe file
  252. getEmployeeListData();
  253. },
  254. error: function (xhr, status, error) {
  255. $("#ResultDiv").empty().text(xhr.responseJSON.error);
  256. }
  257. });
  258. }
  259. function getEmployeeListData() {
  260. var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Employee')/items";
  261. $.ajax({
  262. url: fullUrl,
  263. type: "GET",
  264. headers: {
  265. "accept": "application/json;odata=verbose",
  266. "content-type": "application/json;odata=verbose",
  267. },
  268. success: onQueryEmpSucceeded,
  269. error: onQueryEmpFailed,
  270. });
  271. }
  272. function onQueryEmpSucceeded(data) {
  273. var listItemInfo = '';
  274. var divTableBody = "";
  275. var divTableHeader = "<table id='example' class='display' style='width:100%'>" +
  276. "<thead><tr><th>Action</th><th>Id</th><th>Title</th><th>EmpName</th><th>Gender</th><th>EmpDOJ</th></tr></thead><tbody>";
  277. $.each(data.d.results, function (key, value) {
  278. divTableBody = divTableBody + "<tr><td> <a href='javascript: DeleteListItemUsingItemId(" + value.Id + ")'>Delete </a> || <a href='javascript: UpdateEmployeeListData(" + value.Id + ")'>Edit </a></td><td>" + value.Id + "</td><td>" + value.Title + "</td><td>" + value.EmpName + "</td><td>" + value.Gender + "</td><td>" + value.EmpDOJ + "</td></tr>"
  279. //listItemInfo += '<b>Title:</b> ' + value.Title + ' – <b>EmpName:</b> ' + value.EmpName
  280. // + '<b>Gender:</b>' + value.Gender + '<b>EmpDOJ:</b>' + value.EmpDOJ + '' + '<br />';
  281. });
  282. listItemInfo = divTableHeader + divTableBody + "</tbody><tfoot><tr><th>Action</th><th>Id</th><th>Title</th><th>EmpName</th><th>Gender</th><th>EmpDOJ</th></tr></tfoot></table>";
  283. $("#divResults").html(listItemInfo);
  284. $('#example').DataTable();
  285. }
  286. function onQueryEmpFailed() {
  287. alert('Error!');
  288. }
  289. function addDepartment() {
  290. var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('Department')/items";
  291. $.ajax({
  292. url: fullUrl,
  293. type: "GET",
  294. headers: {
  295. "accept": "application/json;odata=verbose",
  296. "content-type": "application/json;odata=verbose",
  297. },
  298. success: function onQueryEmpSucceeded(data) {
  299. $.each(data.d.results, function (key, value) {
  300. $('#ddlDepartment').append(new Option(value.DeptName, value.Id));
  301. });
  302. },
  303. error: onQueryEmpFailed,
  304. });
  305. }
Output
How To Save Lookup Field Values In SharePoint Using Rest API
Note
For the lookup type field, the value will be Integer and must be the ID of Lookup item. In the request body, you have to specify it as,
InternalNameOfTheColumn + Id
Meaning that, If your field's internal name is DeptName, in the request, it will be DeptNameId. Value of DeptNameId will be an Integer (Id of the lookup item).

Summary

In this article, we have seen the step-by-step implementation of the lookup field and also pictured the upload.
I hope this helps. If this helps you then share it with others.
Sharing is caring! :)