Getting all values from a lookup field in SharePoint using ECMAScript client object model

I recently had a requirement wherein I had to retrieve all the values of a lookup column of a list and bind it to a dropdown using ECMAScript client object model. The tricky part is that the lookup list and column name are not known and thus are to be retrieved dynamically.

I see that there are articles describing to do the same with a choice field but none for a lookup field. So I tried to figure out a way to it for a lookup field.

First in order to accomplish this we need to find the name or GUID of the list and the column which is being used as a lookup column. The below code is used in order to do that:

var context = SP.ClientContext.get_current();
var list = context.get_web().get_lists().getByTitle(listName);
var field = list.get_fields().getByInternalNameOrTitle(fieldName);

//Cast the above column as a lookup column
var lookUpField = context.castTo(field, SP.FieldLookup);

//Load the above castes lookup field
context.load(field);

//Call executeQueryAsync and pass in success and failure anonymous functions
context.executeQueryAsync(function () {

   //lookUpField.get_lookupList() gives the GUID of the lookedup list
   var lookUpListId = lookUpField.get_lookupList();

   //lookUpField.get_lookupField() gives the title of the lookedup field
   var lookUpFieldName = lookUpField.get_lookupField();

   //The onFieldLoaded function is called where we process the lookedup list and field to retrieve the values
   onFieldLoaded(lookUpListId, lookUpFieldName);
},
function (sender, args) {
   console.log(args);
});

Now that you have got the GUID of the lookedup list and the name of the lookedup field, we go ahead and write the code for retrieving all the values of the lookedup field in the OnFieldLoaded() function.

function onFieldLoaded(listID, FieldName) {
  var list = context.get_web().get_lists().getById(listID);
  var query = new SP.CamlQuery();
  query.set_viewXml('<View/>');

  var listItems = list.getItems(query);
  context.load(listItems,'Include('+FieldName+')');
  context.executeQueryAsync(
  function () {
    for (i = 0; i < listItems.get_count() ; i++){
    console.log(listItems.itemAt(i).get_item(FieldName));
    }
  },
  function (request, error) {
    console.log(error);
  });
}
Advertisements

Auto Suggestion/Auto Complete for SharePoint 2010 Search sites

Introduction:

It will be very useful for the users to have the search being suggested based on the past searches while they are typing in the search text box in a SharePoint search site. Yes I’m talking about the same concept that you find in the Google search but with a limited functionality.

This feature is available as an OOTB feature in SharePoint 2013 enterprise search. Look at this link to know more about this cool feature. The process is completely different though.

Description:

This is a simple JavaScript application which when added to a Content editor web part in home page and in the search results page of your SharePoint search site would display suggestions for the users as they type their search query in the search text box. The suggestion keywords are stored and retrieved from a SharePoint custom list called “Search Keywords”. Look at the below screenshot for a better understanding:

As you can see in the above image, as I type “I love s”, I get “I love SharePoint” and “I love Silverlight” as suggestions. These 2 are retrieved from a SharePoint list called “Search Keywords”.

So how and when are these suggestion keywords stored in the “Search Keywords” list? When a user is searching in the search site and the results page finished loading, the JS code added in the CEWP in the results page would add the search query in the “Search Keywords” list as new list item. Thus the matching suggestion keywords are retrieved from the list as the user is typing in the search text box later.

Limitations:

Since the suggestion keywords are added to a SharePoint list as a new list item every time a user searches, the performance may reduce when 1000’s of items get stored in the list. So it is advised to manually delete few keywords often from the list.

Code:

The code is developed using JavaScript, jQuery, Autocomplete jQuery ui widget, and SharePoint Client object model. There are 2 different JavaScript codes. One is for the search home page and the other is for the search results page.

I have explained the code in two parts in the below blog posts:

Part 1: How to give the Auto suggestion/complete functionality to the Search box with search terms retrieved from a SharePoint list.

Part 2: How to store the users’ searched queries to a SharePoint list dynamically and then show them as suggestions in the search box while searching.

Since it is purely a client side application, we can simply deploy it by just moving the files. I assume that you have worked with Content editor web part before. You need to create 2 CEWPs, one for search home page and the other for the search results page. I have explained the deployment process through the below steps:

Deployment process:

  1. Download the SPAutosuggestion.zip file and unzip it.
  2.  Create a folder called SPAutosuggestion under the layouts folder of your SharePoint server.
  3. Copy the files jquery-1.7.js, jquery.ui.autocomplete.js, jquery.ui.core.js, jquery.ui.complete.js, jquery.ui.widget.js, and jquery-ui.CSS from the unzipped folder in to the above create folder.
  4. Go to your SharePoint search site and create a list called “Search Keywords”
  5. Go the search home page and edit the page.
  6. Add a Content editor web part in to the page.
  7. Click on “Click here to add new content” as shown in the below image:  
  8. Now in the ribbon control click on HTML -> Edit HTML Source as shown below:  
  9. In the HTML source editor window copy the content of the AutoSuggectionLandPage.js which would be present in the folder unzipped in step 1.
  10. Click on “Save & Close” under the page tab in the top ribbon.
  11. Go to the search results page of you SharePoint site and edit it.
  12. Repeat step 6 to 10. But instead of copying the content of AutoSuggectionLandPage.js, copy the content of AutoSuggestionResultsPage.js.
  13. Search with different queries twice or thrice to see them getting suggested as you type in the search text box.

Auto Complete/Suggestion in SharePoint 2010 Search Text box with jQuery – Part 2

As I told, here is the second part of the Auto Complete/Suggestion functionality in SharePoint 2010 Search Text box using jQuery. The first post can be found here.

In this blog post I will explain how to attach the auto complete/suggestion functionality to the search text box in the results page of the Search site. Also, we will see how to add the search query into the Search Keywords list so that the suggestion terms need not be added manually by the users. The code implemented here would be used in the search results page.

UPDATE: I have published this application here in CodePlex as well blogged about it briefly over here about the functionality as well as the deployment steps. Check it out if you do not want to get in to the coding side.

I’m going to explain only the modifications that I have done to the code in the previous post.

1. Modify the onQuerySucceeded function as shown below. I have described the code in comments


function onQuerySucceeded(sender, args) {
   listItemEnumerator = collListItem.getEnumerator();
   // declare a bool variable which we will use later
   termPresent = false;
   // get the query string value of key 'k' which has the search query and store in a variable
   // after decoding it
   srchTerm = decodeURI(JSRequest.QueryString["k"]);
   while (listItemEnumerator.moveNext()) {
       oListItem = listItemEnumerator.get_current();

   // check if the value in the Title columns in equal to search query
   // by converting them in to lowercase
   if( oListItem.get_item('Title').toLowerCase() == srchTerm.toLowerCase())
   {
      // if they are equal then change the value of the bool variable to true
      // which means the search query need not be added to the Search Keywords list
      termPresent = true;
   }
   listItemInfo += ',' + oListItem.get_item('Title');
 }

   $(".ms-sbplain").autocomplete({
   source: listItemInfo.split(",")
   });

   // check the value of the bool variable, if it is false then call the createListItem function
   // which will add the list item to the Search Keywords list
  if(termPresent == false)
  {
    createListItem(srchTerm);
  }
 }

2. Create the createListItem function with the below code.

function createListItem(srchTerm)
 {
   // create a new list item to be added in the Search Keywords list
   itemCreateInfo = new SP.ListItemCreationInformation();
   // add the item to the oList which is the Search Keywords list
   this.oListItem = oList.addItem(itemCreateInfo);
   // set the value of the title column of the list item to the search query
   oListItem.set_item('Title', srchTerm);
   // update the the list item
   oListItem.update();
   // load the list item
   clientContext.load(oListItem);
   // declare the delegates to be executed on success and on failure
   clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreateSucceeded), Function.createDelegate(this, this.onQueryFailed));
 }

3. Create an empty onCreateSucceeded function.

function onCreateSucceeded() {
 // just an empty function
 }

Here is the complete code without comments.

<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery-1.7.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.core.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.widget.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.position.js"></script>
<script type="text/javascript" src="/_layouts/SPAutoSuggestion/jquery.ui.autocomplete.js"></script>
<link href="/_layouts/SPAutoSuggestion/jquery-ui.CSS" rel="stylesheet" type="text/css" />

<script type="text/javascript">
JSRequest.EnsureSetup();
var clientContext;
var oList;
var camlQuery;
var listItemInfo = '';
var listItemEnumerator;
var termPresent;
var srchTerm;
var oListItem;
var itemCreateInfo;

$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(Post_COM_Load, "sp.js");
});

function Post_COM_Load() {
clientContext = new SP.ClientContext.get_current();
oList = clientContext.get_web().get_lists().getByTitle('Search Keywords');

camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View/>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(Title)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {

listItemEnumerator = collListItem.getEnumerator();

termPresent = false;

srchTerm = decodeURI(JSRequest.QueryString["k"]);
while (listItemEnumerator.moveNext()) {
oListItem = listItemEnumerator.get_current();
if( oListItem.get_item('Title').toLowerCase() == srchTerm.toLowerCase())
{
termPresent = true;
}
listItemInfo +=
',' + oListItem.get_item('Title');
}

$(".ms-sbplain").autocomplete({
source: listItemInfo.split(",")
});

if(termPresent == false)
{
createListItem(srchTerm);
}
}

function createListItem(srchTerm)
{
itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', srchTerm);
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreateSucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onCreateSucceeded() {
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

4. The above code has to be added to a Content Editor Web Part in the results page of your Search site.

5. After you do a search with a query text, for example “Microsoft SharePoint” in your search site.

you can see that the query text has been added in the Search Keywords list as shown below

which would also eventually appear in the suggestions list as you type in your search text boxes as shown below.