OPEN TO WORK

Available for new opportunities! Let's build something amazing together.

How to Retrieve a Lookup Field Value in JS LINK

CSR JavaScript JS LInk Styling
post

This post is over a year old, some of this information may be out of date.

This week I received a question from someone asking me about how you could retrieve the value from a lookup field in a JS Link field rendering file.

Solution

Retrieving the value from a lookup field is easier than it used to be when working with XSL in SharePoint 2007 / 2010. With the new ways of rendering your items / fields, you don’t have to remove the prefixes (item id ;#) anymore.

What you have to do is check if the object you retrieve contains data. Once you know that it contains data, you can obtained the value(s). Here is a code sample of how you could do it:

var lookupSample = lookupSample '' {};
lookupSample.CustomizeFieldRendering = function () {
// Intialize the variables for overrides objects
var overrideCtx = {
Templates: {
Fields: {
'singleLookupValue': {
'View' : lookupSample.singleLookupValue
},
'multiLookupValue': {
'View' : lookupSample.multiLookupValue
}
}
}
};
// Register the override of the field
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
}
lookupSample.singleLookupValue = function (ctx) {
var output = [];
var field = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
// Check if field contains data
if (field.length > 0) {
// field[0].lookupId -> gives you the linked item ID
var lookupValue = field[0].lookupValue;
}
// Push the value to the array
output.push(lookupValue);
return output.join('');
}
lookupSample.multiLookupValue = function (ctx) {
var output = [];
var field = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
// Check if field contains data
if (field.length > 0) {
output.push('<ul>');
for (i = 0; i < field.length; i++) {
output.push('<li>');
output.push(field[i].lookupValue);
output.push('</li>');
}
output.push('</ul>');
}
return output.join('');
}
lookupSample.CustomizeFieldRendering();

In the code I showed you two examples:

  • The first one singleLookupSample can be used when you’re working with a single lookup value;
  • The second one multiLookupSample can be used when you’re working with multi lookup values. The result of the rendering looks like this:
Show image Lookup Value Example
Lookup Value Example

Related articles

Report issues or make changes on GitHub

Found a typo or issue in this article? Visit the GitHub repository to make changes or submit a bug report.

Comments

Elio Struyf

Solutions Architect & Developer Expert

Loading...

Let's build together

Manage content in VS Code

Present from VS Code