In my previous post, we saw how to display items from a sharepoint list using KO. In this post, we will see how to add items in the list. This demo is in continuation with the previous one.
For your reference, the posts in this series are:
- Part I – Displaying Data from SP list.
- Part II – Adding Data to SP list. (this one)
- Part III – Removing Data from SP list.
First, lets go through the changes made in the previous code for incorporating this functionality.
- A button “Add State” is added. This button updates the view model and add a new country-state in the existing table. It does not update the SP list.
- Another button “Submit to Sharepoint” is added. This button actually updates the data in the sharepoint list.
- Now the country and states are displayed in text box so that user can add new ones. Edit functionality is not included in this post.
- Two divs are added for displaying success and failure messages.
- styling is added for success and failure messages. Not much changes are done here.
- Another property “IsUpdated” is added in the “CountryList” class. This property is used to keep tab of newly created items in the view model. Using this, we will send only changed items to the server and not the complete list of data.
- In the view model, “UpdateSPList” function is added. This function will be called on click of “Submit to SP” button.
- “changedCountries” array holds all the newly added items. “emptyValues” is a boolean variable which maintains if any of the country name or state name is blank. If yes, then that entry is not sent to SP and a message is displayed to the user.
- “SubmitDataToSP” is a function which actually uses sharepoint CSOM and adds new items in the list.
- On click of “Add State” button a function “AddCountries” of view model is called. The parameters passed are $data (which is the current item inside a foreach loop), country name, state name and true as the value of “IsUpdated” property. For more details on ‘click’ event, check this link.
- Similarly on click of “Submit to SP” we call, “UpdateSPList” method of the view model.
So, now the complete code is as follows:
The result page will look like:
Please note that this might not be the completely optimized way to achieve this functionality. The goal here is to demo use of KO with sharepoint. In the next post, we will modify this code further to achieve delete functionality.
Hope this helps!!