Search result for:
Press ESC to close Search Result or press here

n8design


Art, Design, Media, Web & SharePoint … by Stefan Bauer
11. December 2011

Retrieve Managed Metadata using JavaScript and SPServices

In one of my last projects I ran into an interesting question regarding the taxonomy store. Will it be possible to get all taxonomy data by using pure JavaScript?

SharePoint has a great JavaScript object model for different purposes but how deep is this integration when an access to service applications like the Managed Metadata Service is required. The simple answer on this is: Not enough. Due the strict project plan we decided to use a Silverlight web part, which is capable to access the taxonomy store. This solution worked well but I wasn’t pleased by that.

Time passed by and the question left unanswered to me. At the SharePoint Conference I meet Mark D. Anderson the founder of SPServices. He told me that this Jquery library should be capable of accessing the Taxonomy Client Web Service. This was the last missing information that I needed to access the Taxonomy Store and this is my solution.

The challenges

Basically there are three gaps to take to get information from the taxonomy store.

  • Get all required data to access Taxonomy Service
  • Access the TaxonomyClientService using JavaScript
  • Handle the XML result from the web service

These goals sound simple but when it comes to JavaScript and the Taxonomy Store a lot of creativity is needed to get this done. At the end I’m really pleased with my solution. The following explanations will use a simple Metadata Field called ‘Color’.

Taxonomy in Term Store Management

Taxonomy in Term Store Management

Get all data to access Taxonomy Service

In SharePoint 2010 Managed Metadata information will always be used in columns and the configuration to the managed metadata service is directly stored in the field configuration. By accessing those site collections columns all required information can be retrieved with a dynamic and flexible approach. The following code access a field named “Color” in my site collection and returns the xml schema of the field.

var fieldCollection;

var colorField = null;
 var texconfig = null;

 // Delay Script Execution until sp.js is fully loaded
 ExecuteOrDelayUntilScriptLoaded(getColor, "sp.js");

 function getColor() {
     // Load the client context
     var clientContext = SP.ClientContext.get_current();
     if (clientContext != undefined && clientContext != null) {
         // Load the root web.
         var webSite = clientContext.get_site().get_rootWeb();;

         // Select 'Color' Field from the root web site colins
         fieldCollection = webSite.get_fields();
         this.colorField = fieldCollection.getByInternalNameOrTitle("Color");

         // Load the field or throw error
         clientContext.load(this.fieldCollection);
         clientContext.load(this.colorField);
         clientContext.executeQueryAsync(
             Function.createDelegate(this, this.OnLoadSuccess),
             Function.createDelegate(this, this.OnLoadFailed)
             );
     }
 }

 function OnLoadSuccess(sender, args) {
     var fieldInfo = '';
     // Get Schema XML from the field
     var fieldschema = colorField.get_schemaXml();
     // Parse it with the Taxonomy Configuration Object
     texconfig = TaxConfiguration;
     texconfig.Configuration = fieldschema;
     texconfig.ParseConfiguration();
    // Do something with the field information

 }

function OnLoadFailed(sender, args) {
     alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
 }

For parsing this xml schema of the field I created a simple helper class that query for all required properties to access the taxonomy store. The XML parsing is pretty much straight forward and that’s how the code looks like:

var TaxConfiguration = {
     SspId: "",
     GroupId: "",
     TermSetId: "",
     Configuration: "",
     ParseConfiguration: function () {

         xmlDoc = $.parseXML(this.Configuration);
         xml = $(xmlDoc);

         var properties = xml.find("Property");

         for (i = 0; i < properties.length; i++) {

             propertyName = properties[i].firstChild.textContent == undefined ?
properties[i].firstChild.text : properties[i].firstChild.textContent;
             propertyValue = properties[i].lastChild.textContent == undefined ?
properties[i].lastChild.text : properties[i].lastChild.textContent;

             if (propertyName == propertyValue) {
                 propertyValue = "";
             }

             switch (propertyName) {
                 case "SspId":
                     this.SspId = propertyValue;
                     break;
                 case "GroupId":
                     this.GroupId = propertyValue;
                     break;
                 case "TermSetId":
                     this.TermSetId = propertyValue;
                     break;
             }
         }

     }
 }

Somehow the xml parsing in IE and chrome is different; therefore I need to check if ‘textContent’ or simply ‘text’ exists in my jquery object. After this gap was taken everything was ready to access the taxonomy service application.

Access the TaxonomyClientService using JavaScript

As mentioned before SPServices is powerful library to access the SharePoint Web Services using JavaScript and make use Jquery. There are ways to access asp.net web services by pure JavaScript but it’s a more comfortable way to do this.

To access all hierarchy levels of a terms stored two different web service calls needs to be made because there is no web service available that returns all the information at once. Those different methods that need to be called are:

The documentation of the result returned by the web service can be found in the MS-EMMWS: Microsoft Enterprise Managed Metadata Web Service Protocol Specification. It takes a while to figure out which property is used for what. The following xml attributes will be consumed by my script:

  • a9
    Guid of the term
  • a32
    Name of the term
  • a25
    Parent termID
  • a69
    Term has child terms

After I figured out those xml attributes I was able to build my script and here is it:

function GetTermsRecursive(sspId, termSetId) {

     var terms = new Array();
     var returnValue;

     $().SPServices({
         operation: "GetChildTermsInTermSet",
         sspId: sspId,
         termSetId: termSetId,
         lcid: 1033,
         completefunc: GetData
     });
 }

 function GetChildTermsRecursive(sspId, termSetId, roottermId) {

     var terms = new Array();

     $().SPServices({
         operation: "GetChildTermsInTerm",
         sspId: sspId,
         termId: roottermId,
         termSetId: termSetId,
         lcid: 1033,
         completefunc: GetData
     });

     return terms;

 }

 function GetData(xData, Status) {
     if (Status == "success") {

         terms = new Array();

         xmlData = xData;

         // Fix for different XML parsing in IE and Chrome
         termsContent = $.parseXML(xmlData.responseText).firstChild.textContent == undefined ?
                             $.parseXML(xmlData.responseText).text :
                             $.parseXML(xmlData.responseText).firstChild.textContent;

         termsXML = $.parseXML(termsContent);
         $termsXML = $(termsXML);
         console.log($termsXML);

         childTerms = $termsXML.find("T");
         parentTermId = null;

         filterOutput = "<ul>";

         for (i = 0; i < childTerms.length; i++) {

             termName = $(childTerms[i]).find("TL");
             hasChildTermsXml = $(childTerms[i]).find("TM");

             // request if child terms are available
             hasChildTerms = $(hasChildTermsXml).attr("a69");

             var tsTerm = new Object();

             // Requesting actual term id
             tsTerm.termId = $(childTerms[i]).attr("a9");

             // Requesting term name
             tsTerm.termName = termName.attr("a32");

             // Setting Parent Term ID
             parentTermId = $(hasChildTermsXml).attr("a25");

             filterOutput += "<li id='" + tsTerm.termId + "'>" + tsTerm.termName;

             // If child terms are avaliable query child terms
             if (hasChildTerms != undefined && hasChildTerms == "true") {

                 // Request child Terms
                 tsTerm.child = GetChildTermsRecursive(taxconfig.SspId, taxconfig.TermSetId, tsTerm.termId);
                 tsTerm.hasChildTerms = true;

             } else {

                 tsTerm.child = null;
                 tsTerm.hasChildTerms = false;

             }

             filterOutput += "</li>";
             terms[i] = tsTerm;

         }

         filterOutput += "</ul>";

         // If parent element is specified query for parent element
         if (parentTermId != undefined || parentTermId != null) {

             $("#" + parentTermId).append(filterOutput);

         } else {

             currentFilter = $("#filter").html();
             $("#filter").html(currentFilter + filterOutput);

         }
         return terms;

     }
 }

So that’s all needed to return and output the result in SharePoint. For displaying those terms I added a HTML Form web part to the page that contains a simple div element with the id called filter.

Output of javascript.from the Managed Meta Data Service

Output of JavaScript.from the Managed Meta Data Service

I decided to write a simple list to the defined div but it can be transformed to any other structure.

Conclusion

What looks like a complex problem at the beginning was easy to solve by using SPServices. In future projects now I’m able to use pure JavaScript to access Managed Metadata Service. The code for that is highly reusable too. I’m now able to access any site collection field based on managed metadata by using my TaxConfiguration object. It’s flexible and dynamic and hard coding of the required information to access the managed metadata service is not needed anymore. SPServices is also capable to boost productivity. In future if in need to decide to use Silverlight or JavaScript to access the Managed Metadata Service I will prefer to use JavaScript for a simple reason. Silverlight wasn’t made to write html to a web page. I think this is a misuse of Silverlight in this case.

If you like to download and play around yourself you can download the scripts packed up in a web part. All that needs to be done in the web part is to change the references to the SPServices and the name of the field in the getColor function.

Download JavaScript Taxonomy Web Part

Have fun with the taxonomy store !!!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comments
  • David Lozzi commented at 20. February 2012 at 19:33

    Thanks for the great article. I combined this with some linking to allow users to filter their page based on metadata, check out my project at http://metadatapagefilter.codeplex.com/.

  • Antti Laurila commented at 2. August 2012 at 10:08

    Hi! I’m not allowed to add webparts in our sharepoint subsite, but the need for this kind of solution is desperate. I tried to combine these scripts together but with very bad results.

    I got the script running – it gave errors and I managed to get rid of them, but still without any results on the page. I created a div with the id: #filter but no results with that either.

    What are the parts that need to be customized in order to make this script running – the site columnname of course, but anything else?

    Great job on the script, this should be a native solution to Sharepoint IMHO.

    • Stefan Bauer commented at 2. August 2012 at 11:08

      If you referring to the web part that David Lozzi created you should get in contact with him.
      What you need to change in my script can be found in the function getColor(). There you need to change the following section.

      // Select ‘Color’ Field
      fieldCollection = webSite.get_fields();
      this.colorField = fieldCollection.getByInternalNameOrTitle(“Color”);
      You need to change the name of the field from “Color” to your field name, which has to be a site collection field because otherwise the code slightly change.
      What i have seen in the script is that i referring to the SPServices library which was in my case stored in the _layouts folder. This can be found in the second line of the script.

      needs to be changed to

      This will get SPServices directly from a content distribution network but it could be any place where your SPServices Library is located.
      If you have further trouble you can send me the script and i’ll have to take a look.

  • Antti Laurila commented at 3. August 2012 at 09:06

    Hello again and a huge thanks to your super-fast reply. I was referring to the solution on this page and your response gave me enough confirmation to keep on trying to find the solution.

    After some debugging I got the script working. Thanks again for your great script, saves me from doing things twice with Managed Metadata and Custom Lists.

    There were a slight typo in the scripts ‘taxconfig’ variable was referred to as ‘texconfig’ in some places, after these alterations things started to happen!

    • Stefan Bauer commented at 3. August 2012 at 15:11

      You are welcome. Thank you for the comment on the typo i need to check it and replace it, when it cause troubles. ;)

  • Joey Jaxson commented at 17. August 2012 at 22:48

    Very cool, thanks for posting this. The one thing that I did notice is that the get_schemaXml() is super slow. The data returned for me is over 1 mb and is taking around 7 seconds to return the XML and I only have 25 or so terms. Any idea on ways around that or alternatives that would be more efficient? Thanks again for the post.

    • Stefan Bauer commented at 17. August 2012 at 23:23

      get_schemaXml only gets the configuration of the field which will never be more than some bytes of XML data. This also wont contain any term. Would it be possible to see your get_schemaXml result somehow?

  • Joey Jaxson commented at 23. August 2012 at 20:19

    You are right it was not the get_schemaXML() it was the
    fieldCollection = webSite.get_fields();
    this.colorField = fieldCollection.getByInternalNameOrTitle(“Color”);

    that was returning 1.2 MB of data which makes sense because that returns every field for the site. I ended up just hard coding the ids of the sspid and the TermSetId which makes it super lightweight and ultra fast.

    Thanks again for the post — Good stuff!

    • Stefan Bauer commented at 23. August 2012 at 22:18

      Oh thanks for your comment. I’ll check that but maybe it would work and be for lightweight if you try:
      webSite.get_fields().GetByInternalNameOrTitle(“Color”).

  • Jussi Palo commented at 4. January 2013 at 11:44

    I can’t seem to figure out how to cache stuff to prevent the massive amount of ajax queries to Managed Metadata Service. Challenge is that functions are called recursively, so in the completefunc of GetChildTermsInTermSet SPServices call in function GetTermsRecursive function I cannot cache stuff as it is still loading.

    Any thoughts?

    • Stefan Bauer commented at 4. January 2013 at 12:55

      Great input. The story behind is that we had a small amount of terms that we had in the term store and are forced to create a SandBox Solution. The problem as you sure know is that you cannot access taxonomy service within a SandBox. In my opinion it depends on the use case how you read the terms. For example if you like to get the terms in a tree view or something link that you can partially load the data from the taxonomy store which doesn’t improve number of ajax requests but improves the loading time. Then you will use the same way as SharePoint does out of the box.
      If you like to get a specific term and all the sub terms it will be much faster to set a specific filter and then recurse through the sub tree.
      If you like to get only terms that currently will be used in your site collection from a specific term set then it’s much faster to query the terms from the TaxonomyHiddenList which exists on root level of every site collection.

  • Eduardo Gonzalez commented at 22. January 2013 at 00:25

    Hi Stefan,

    This post is great and complete. But what I don’t understand, is why im not get my taxonomi return, it always says Column doesn’t exist.

    I have almost the same as the first image on my taxonomy term store.. “Taxonomy_bwXML….” instead of “Managed Metadata Store” and Taxonomies instead of “My Taxonomies”, and Color as Color

    what can I do??

    what do you mean with site collection field .. is it the same as the group name in my taxonomy term store??

    Thanks
    Eduardo Gonzalez

  • Eduardo Gonzalez commented at 22. January 2013 at 19:39

    Nice Post, everything works just Perfect.

    Thanks for your help