In this blog I would like to share the code to add the custom fields on SharePoint host web list using SharePoint hosted app.
In *.aspx page add HTML Button
<button type="button" id="btnCreate">Add Field</button>
Write below code on *.js file,
- //get Current Context
- var context = SP.ClientContext.get_current();
- // This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
- $(document).ready(function () {
- console.log("page loading...");
- $("#btnCreate").click(function () {
- addField();
- });
- });
- //this method is used to add the fields on custom list
- function addField() {
- //Get host web URL
- var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
- //get app context using host web url
- var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
- //get current web
- var currentWEB = appCtxSite.get_web();
- //get list from host web
- var list = currentWEB.get_lists();
- //load the list
- context.load(list);
- context.executeQueryAsync(function () {
- //get custom list by name
- var currentList = list.getByTitle("sampleList");
- //get field collection from current list
- var fldCollection = currentList.get_fields();
- //set the type and field details
- var f1 = context.castTo(fldCollection.addFieldAsXml('<Field Type="Text" DisplayName="Person Name" Name="PersonName" />', true, SP.AddFieldOptions.addToDefaultContentType), SP.FieldText);
- f1.set_title("PersonName");
- //update
- f1.update();
- context.executeQueryAsync(function () {
- console.log("Field Creation Success");
- },
- function (sender, args) {
- console.log("Field Creation failed : " + args.get_message());
- });
- }, function (sender, args) {
- onfail(sender, args);
- });
- }
- // This function is executed if the above call fails
- function onfail(sender, args) {
- alert('Failed to add field in list. Error:' + args.get_message());
- }
- // this method used split the query string
- function manageQueryStringParameter(paramToRetrieve) {
- var params = document.URL.split("?")[1].split("&");
- var strParams = "";
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve) {
- return singleParam[1];
- }
- }
- }
Summary
In this blog we have explored how to add the custom fields in host web list using SharePoint hosted app with JavaScript Object model. Happy coding !!

Kaviya BalasubramanianPosted Sep 20, 2016, 5:09 AM
Thank you :)
Tarun DPosted Sep 20, 2016, 4:54 AM
Thanks for sharing..