Skip to content

Instantly share code, notes, and snippets.

@MartinBodocky
Created December 20, 2013 15:58
Show Gist options
  • Save MartinBodocky/8056791 to your computer and use it in GitHub Desktop.
Save MartinBodocky/8056791 to your computer and use it in GitHub Desktop.
How to create and get Field Choice in SharePoint 2013 by REST
GetFieldsFromCollectionREST = function (restUrl, properties) {
var values = [];
select = "$select="
if (properties.length > 1)
select += _(properties.slice(1)).reduce(function (memo, item) { return memo + "," + item }, properties[0]);
else
select += properties[0];
if (restUrl.indexOf('?') > -1)
restUrl = restUrl + "&" + select;
else
restUrl = restUrl + "?" + select;
$.ajax({
url: restUrl,
type: "GET",
async: false,
headers: {
"accept": "application/json;odata=verbose",
},
success: function (data) {
if (data.d && data.d.results) {
_(data.d.results).each(function (res) {
var value = {};
_(properties).each(function (fst) {
value[fst] = res[fst];
});
values.push(value);
});
}
},
error: function (err) {}
});
return values;
};
PostCreateByREST = function (restUrl, data) {
var result;
$.ajax({
url: restUrl,
async: false,
type: "POST",
data: data,
contentType: "application/json;charset=utf-8;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
},
success: function (data) {
result = true;
},
error: function (err) {
result = false;
}
});
return result;
};
//usage
var choiceFieldValue = GetFieldsFromCollectionREST("<siteUrl>/_api/Web/Lists/GetByTitle('<listName>')/fields?$filter=TypeAsString eq 'Choice'", ["Title", "Choices"]);
var choices = choiceFieldValue.results;
var dataFieldCreation = "{ '__metadata': { 'type': 'SP.FieldChoice' }, 'Title': 'New choice Field', 'FieldTypeKind': 6,'Required': 'false', 'Choices': { 'results': ['Choice1', 'Choice2', 'Choice3'] } }";
var success = PostCreateByREST("<siteUrl>_api/Web/Lists/GetByTitle('<listName>')/fields", dataFieldCreation);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment