How would you get a list of all the possible choices from a choice field (e.g. Task list Priority or Status fields) using javascript client object model?
2 Answers
You can get this from SP.FieldChoice.get_choices() (SPFieldChoice inherits SPFieldMultiChoice)
To get that object you need to use context.castTo to cast SP.Field to SP.FieldChoice.
// Setup context and load current web var context = new SP.ClientContext.get_current(); var web = context.get_web(); context.load(); // Get task list var taskList = web.get_lists().getByTitle("Tasks"); // Get Priority field (choice field) var priorityField = context.castTo(taskList.get_fields().getByInternalNameOrTitle("Priority"), SP.FieldChoice); // Load the field context.load(priorityField); // Call server context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod)); function onSuccessMethod(sender, args) { // Get string arry of possible choices (but NOT fill-in choices) var choices = priorityField.get_choices(); alert("Choices: (" + choices.length + ") - " + choices.join(", ")); } function onFailureMethod(sender, args) { alert("oh oh!"); } - 3I didn't even know about context.castTo, this is brilliant. Thanks!eirikb– eirikb2012-10-05 14:15:18 +00:00Commented Oct 5, 2012 at 14:15
- 3The above code needs to have a
context.load(priorityField);before theexecuteQueryAsync! Otherwise you will get a property error when doing theget_choices()user16654– user166542013-04-26 16:41:23 +00:00Commented Apr 26, 2013 at 16:41 - You're right user16654, the code need to be used
context.load(priorityField);beforeexecuteQueryAsynctbbt– tbbt2014-12-18 03:46:13 +00:00Commented Dec 18, 2014 at 3:46
On SharePoint 2013, we can use the REST API. An example would be with a GET request similar to this:
/_api/web/lists/getbytitle('task')/Fields?$filter=Title eq 'Fieldname'
The request returns the field metadata. For more detail, view this link:
http://www.ozkary.com/2015/10/sharepoint-choice-field-options-with-angularjs.html?m=1
- I can't get this to work with an App Web. Says permission denied with Admin credsMichael Colbs– Michael Colbs2016-07-06 17:24:47 +00:00Commented Jul 6, 2016 at 17:24
- 1Keep in mind that calls to the SP API need to run under the security context of the user. You should login to SP. Open another tab (same browser) and enter the url with the apo call to test the access. The tabs should maintain the same security context. Double check that an Authorization header is send to the server with an auth token (dev tools)ozkary– ozkary2016-07-07 01:54:03 +00:00Commented Jul 7, 2016 at 1:54