CAML Query to Filter Lookup Field by Id using JSOM in Office 365 / SharePoint 2013

Introduction

Few days ago, I wrote a post about how to Create a new lookup field using JSOM in Office 365. Continuing with the same scenario, we have two related libraries: Documents and Pages, and the requirement is to see for every page one list of related documents.

So, the first step, was creating a lookup value in order to allow us to relate two libraries. And the next step, which is the post topic, is to use JSOM (JavaScript) code in a script webpart to query Documents library filtering by current page id, that means filtering by using Lookup ID column.

image

If you look at the picture, this is how lookup field is filled in the Documents library.

And here is the code we need to use using a Script WebPart or Content Editor WebPart inside the Pages Library documents or pages.

Note: This is important to note that this code is using some context variables related to current page id and this code is only working if that is inside a page. For example, if we have a page like that:

image

Note: We can try / debug our code using F12 (Developer Tools in Chrome or IE).

Code

Here is the code to achieve the image results:

//Auxiliary functions to build the icon URL
var pngs = ["doc", "docx", "dot", "dotx", "pdf", "ppt", "pptx", "pub", "xls", "xlsx"];
var gifs = ["asp", "aspx", "bmp", "css", "gif", "htm", "ini", "jpe", "jpeg", "jpg", "js", "log", "png", "tif", "tiff", "txt", "vsd", "vsdx", "xml", "xsl", "xslt"];
var getIconUrl = function (docIcon) {
var returnImageUrl = "/_layouts/15/images/icgen.gif";
var nExt = docIcon;
if (pngs.indexOf(docIcon) >= 0) {
returnImageUrl = "/_layouts/15/images/ic" + docIcon + ".png";
}
else if (gifs.indexOf(docIcon) >= 0) {
returnImageUrl = "/_layouts/15/images/ic" + docIcon + ".gif";
}
return returnImageUrl;
};
// Code to query documents library using lookup in the CAML query and representing the information in a div container.
var containerDivSelector = "#relatedDocumentsContainer";
var documentLibrary = "Documents";
var lookupInternalName = "StandardPageLookup";
// Get SharePoint context
var ctx = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
// Get Documents Library
var oList = ctx.get_web().get_lists().getByTitle(documentLibrary);
var camlQuery = new SP.CamlQuery();
// CAML query to get only the documents related to the current page (that means, this code is valid to be executed inside every page)
// _spPageContextInfo.pageItemId is the current page ID
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'' + lookupInternalName + '\' LookupId=\'TRUE\' /><Value Type=\'Lookup\'>' + _spPageContextInfo.pageItemId + '</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>');
var collListItem = oList.getItems(camlQuery);
// Include only needed fields to reduce network load
ctx.load(collListItem, 'Include(FileRef,' + lookupInternalName + ',DocIcon,FileLeafRef)');
ctx.executeQueryAsync(function () {
//Iterate results and build the div container
var listItemEnumerator = collListItem.getEnumerator();
var listItemInfo = "";
var finalHtml = "";
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var docIcon = oListItem.get_item('DocIcon');
var url = oListItem.get_item('FileRef');
var fileName = oListItem.get_item('FileLeafRef');
var lookupVal = oListItem.get_item(lookupInternalName);
var relatedId = lookupVal.get_lookupId();
finalHtml += '<div relatedpageid="' + relatedId + '" class="content-item">';
finalHtml += ' <div class="image">';
finalHtml += ' <img src="' + getIconUrl(docIcon) + '" />';
finalHtml += ' </div>';
finalHtml += ' <a class="doc-title" href="' + url + '" target="_blank">';
finalHtml += fileName;
finalHtml += ' </a>';
finalHtml += '</div>';
}
console.log(finalHtml);
jQuery(containerDivSelector).html(finalHtml);
},
function (sender, args) {
console.log('Request collListItem failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);

 

Author: José Quinto
Link: https://blog.josequinto.com/2015/12/17/caml-query-to-filter-lookup-field-by-id-using-jsom-in-office-365-sharepoint-2013/
Copyright Notice: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.