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,
-
- var context = SP.ClientContext.get_current();
-
- $(document).ready(function () {
- console.log("page loading...");
- $("#btnCreate").click(function () {
- addField();
- });
- });
-
-
- function addField() {
-
- var hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
-
- var appCtxSite = new SP.AppContextSite(context, hostWebUrl);
-
- var currentWEB = appCtxSite.get_web();
-
- var list = currentWEB.get_lists();
-
- context.load(list);
- context.executeQueryAsync(function () {
-
- var currentList = list.getByTitle("sampleList");
-
- var fldCollection = currentList.get_fields();
-
- var f1 = context.castTo(fldCollection.addFieldAsXml('<Field Type="Text" DisplayName="Person Name" Name="PersonName" />', true, SP.AddFieldOptions.addToDefaultContentType), SP.FieldText);
- f1.set_title("PersonName");
-
- 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);
- });
- }
-
-
- function onfail(sender, args) {
- alert('Failed to add field in list. Error:' + args.get_message());
- }
-
-
- 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];
- }
- }
- }
Note - In app manifest file provide full control permission to the web as shown in below,
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 !!