Monday, January 23, 2012

Filtered lookup – jquery and client object model

I’ve created filtered lookup based on extended version of cascaded lookup from blog.libinuko.com. It’s more general and it supports both versions of lookup field (dropdown / autocomplete).

Thanks to the following scripts:
http://www.sharepointboris.net/js/spcd
http://blog.libinuko.com/2011/01/29/sharepoint-2010-how-to-create-cascading-lookup-field-using-client-object-model

Reference jquery.js and SP.js from your page.

<SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" Localizable="false" />

Javascript code for filtered lookup:
// Filtered lookup

function FilteredLookup(fieldTitle, listName, query) {
// Set variables
this.fieldTitle = fieldTitle;
this.listName = listName;

// Load filtered items for target lookup field
var clientCtx = new SP.ClientContext.get_current();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query>" + query + "</Query></View>");

var list = clientCtx.get_web().get_lists().getByTitle(listName);
this.listItems = list.getItems(camlQuery);
clientCtx.load(this.listItems, "Include(Id, Title)");
clientCtx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

FilteredLookup.prototype.onQuerySucceeded = function (sender, args) {
// Find lookup field
var lookup = $("select[title='" + this.fieldTitle + "']"); // 0-19 items
if (lookup.length == 0) {
// Bind filtered items to lookup field (input / autocomplete)
lookup = $("input[title='" + this.fieldTitle + "']"); // > 20 items
if (lookup.length == 0)
return;
var lookupHidden = $("input[id='" + lookup[0].optHid + "']");
if (lookupHidden.length == 0)
return;

var choices = "";
var listItemEnumerator = this.listItems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var listItem = listItemEnumerator.get_current();
if (choices.length > 0)
choices += "|";
choices += listItem.get_item("Title") + "|" + listItem.get_id();
}
lookup.attr("choices", choices);
}
else {
// Bind filtered items to lookup field (select / option)
var options = "";
var currentValue = lookup.val();
var listItemEnumerator = this.listItems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var listItem = listItemEnumerator.get_current();
options += '<option value="' + listItem.get_id() + '">' + listItem.get_item('Title') + '</option>';
}
lookup.html(options);
lookup.val(currentValue);
}
}

FilteredLookup.prototype.onQueryFailed = function (sender, args) {
alert("Request failed. " + args.get_message() + "\n" + args.get_stackTrace());
}

Sample:
var filterCountry;

function setupLookups() {
filterCountry = new FilteredLookup("Country", "Countries", "<Where><BeginsWith><FieldRef Name='Title' /><Value Type='Text'>A</Value></BeginsWith></Where>");
}

// Attach function on document ready
$(document).ready(
function () {
ExecuteOrDelayUntilScriptLoaded(setupLookups, "SP.js");
});

No comments:

Post a Comment