Have you ever modified a site page in SharePoint, wanting to add the value of a list item field without wanting to parse it to text yourself? I know I have.
And when you get that field using JSOM and just output it to HTML you get that fantastic [Object] output instead of the user name of the people picker field…
This post will help you.
What I’m trying to achieve is to get all list item properties in one call and in text format, not object format, so I don’t have to parse it to text myself.
Step 1: Getting your data
Let’s get some data! I’m using the page context to find out which list I’m in, and I’m using a function getParameterByName to get the “ID” query string variable:
var ctx = SP.ClientContext.get_current(); var list = ctx.get_web().get_lists().getById(_spPageContextInfo.pageListId); var item = list.getItemById(getParameterByName("ID")); ctx.load(item, "FieldValuesAsText");
This is what you typically do. But mind the last line, it doesn’t query for all properties, but just the property FieldValuesAsText.
Step 2: Use fields as text
This returns an object of items as text like so:
var itemAsText = item.get_fieldValuesAsText(); itemAsText.get_item("field_internal_name");
The second line here does exactly the same as with item, but returns text, not objects. Don’t forget to actually execute your query, it’s now shown in my code.
This allowed me to simply override a document set welcome page and insert some formatted tables instead of just all fields under each other. I did not have to bother to think about the different formats of fields, each field came out exactly as I wanted to see it:
And that’s it, simple but elegant. But you have to know how 🙂
Source: get_fieldValuesAsText usage example (SharePoint StackExchange)