Xylos brands

SharePoint - How to Retrieve a Lookup Field Value in JS LINK

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 way 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 values like this:

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:

[caption id="" align="aligncenter" width="263"]Lookup Value Example Lookup Value Example[/caption]

* Originally posted on: http://www.eliostruyf.com/how-to-retrieve-a-lookup-field-value-js-link/ *

Share this blogpost

Also interesting for you

Leave a reply

Your email address will not be published. Required fields are marked.