Is it possible to retrieve every field value of a SharePoint List Item and display them on a web page without specifically calling them individually? I know it is possible to retrieve all the items but with JSOM and Rest you have to call each field you want displayed (ie oListItem.get_item('Title')). I would like all fields to appear automatically so if I add a new field it will appear without having to update the code.
1 Answer
Get a list of fields first, then iterate them, if needed check for conditions (read only, visible etc.) and then display the values:
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle("ListName");
this.listFields = list.get_fields();
clientContext.load(this.listFields);
clientContext.executeQueryAsync(Function.createDelegate(this,
this.onListFieldsQuerySucceeded), Function.createDelegate(this,
this.onListFieldsQueryFailed));
function onListFieldsQuerySucceeded() {
var fieldEnumerator = listFields.getEnumerator();
while (fieldEnumerator.moveNext()) {
var oField = fieldEnumerator.get_current();
var fieldValue = oField.get_item(oField.internalName)
}
}
Lookup field values are displayed in a different way, for example:
var fieldLookup = item.get_item('LastName');
var fieldLookupValue = fieldLookup.get_lookupValue();
So before getting the value of a field, check for it's type:
var fType = oField.get_fieldTypeKind();
if(fType === SP.FieldType.lookup) {
oField.get_item('Department').get_lookupValue()
}
You can find SP.FieldType enumeration here
Hope this helps.
-
Thanks for the help! Is there any way to automatically iterate through all the fields without calling each ones internal name though?– James11Commented Aug 17, 2015 at 13:21
-
1He does not call them by name directly, look at the while loop. The LastName and Department are just an example for how to deal with lookup Commented Aug 17, 2015 at 13:22
-
Thanks I missed that. But when I try to use this code I am getting an Uncaught TypeError: oField.get_item is not a function. I made sure sp.js was loaded before the function but that didn't solve the problem.– James11Commented Aug 17, 2015 at 14:44
-
-
Might be many reasons. Try to debug the code line by line and see where it fails. Commented Aug 17, 2015 at 15:01