1

I am trying to use JavaScript and REST to grab terms out of a Term Set and bind them to a Bootstrap select field in the NewForm.aspx for a list.

Thus far I just cannot pull the terms and bind to field. Any ideas? Thank you Doug

popup from js

1

Here is my sample test script to get terms by JSOM in SharePoint 2013 for your reference.

<script type="text/javascript">
    if (myStronglyTypedObj === undefined) {
        var myStronglyTypedObj = {};
    }

    myStronglyTypedObj = {
        // Object Globals
        "g": {},
        // Pre-initialization functions ensure scripts SharePoint dependencies are loaded
        "preinit": function () {
            // Load necessary libraries
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
                // Register what you need from SharePoint (in this case the term store)
                SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
                // Load the registered items
                SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', myStronglyTypedObj.init());
            });
        },
        // The main Initialization function
        "init": function () {
            /* Check if SP.Taxonomy actually exists yet
             * PLEASE NOTE that it's common that these objects aren't available, even if you've properly loaded them in the "preinit" function.
             * This bit of code checks if the object is available, and if it's not, waits for 200ms and then tries again until this object is loaded
             */
            if (SP.Taxonomy) {
                console.log("SP.Taxonomy ready... continuing scripts...");
                myStronglyTypedObj.therest();
            } else {
                console.log("SP.Taxonomy not ready...  set timeout and try again after 200ms");
                setTimeout(myStronglyTypedObj.init, 200);
            }
        },
        "therest": function () {
            getTerms();
        }
    }

    // Run whatever pre-initialisation checks you need to, and then load "preinit" as the starting point, for instance
    myStronglyTypedObj.preinit();
    function getTerms() {
        var termSetName = "MyTerms";
        var locale = 1033; // your locale. 1033 for English

        var clientContext = SP.ClientContext.get_current();
        var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
        var termStore = taxonomySession.getDefaultSiteCollectionTermStore();
        var termSets = termStore.getTermSetsByName(termSetName, locale);
        var termSet = termSets.getByName(termSetName);
        var terms = termSet.getAllTerms();       
        clientContext.load(termSet);        
        clientContext.load(terms, 'Include(Name,Labels)')

        clientContext.executeQueryAsync(
          function () {
              var enumerator = terms.getEnumerator();
              while (enumerator.moveNext()) {
                  var spTerm = enumerator.get_current();                  
                  var labels = spTerm.get_labels();
                  for (var j = 0; j < labels.get_count() ; j++) {
                      var label = labels.getItemAtIndex(j);
                      if (label.get_isDefaultForLanguage()) {  /* Is default label? */
                          alert(label.get_value());
                      }
                  }

  [![enter image description here][1]][1]            }

          }, function (err) {
              alert(err.get_message());
          });
    }
    </script>
  • Thank you Lee, I will sure give this a try. How would one go about binding the results of getTerms to a dropdown? – Doug Clelland Dec 31 '18 at 13:39
  • You could use jQuery to add options to dropdown, check this link paulund.co.uk/add-and-remove-options-in-select-using-jquery – Lee_MSFT Jan 1 at 0:58
  • Thank you Lee! Works great! the only thing is I cannot get rid of a javascript alert window that shows all the terms one at a time (from your code). I'll add a screen shot above...Thank you Lee – Doug Clelland Jan 2 at 13:50
  • Lee, added image of pop up alerts – Doug Clelland Jan 2 at 13:51
  • Never mind Lee I found my answer all is working as expected! – Doug Clelland Jan 2 at 16:09
0

While it appears it is not an officially supported API, this article provides the following code to asyncronously retrieve data from the term store via REST:

$.ajax({
  url:"https://<your-tenant>.sharepoint.com/_vti_bin/TaxonomyInternalService.json/GetChildTermsInTermSetWithPaging",
  type:"POST",
  headers: {
    "accept":"application/json;odata.metadata=minimal",
    "content-type": "application/json;charset=utf-8",
    "odata-version":"4.0",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
  },
  data:JSON.stringify({
    lcid: 1033,
    sspId: "guid-here", //Term store ID
    guid: "guid-here", //Term set ID
    includeDeprecated: false,
    pageLimit: 1000,
    pagingForward: false,
    includeCurrentChild: false,
    currentChildId: "00000000–0000–0000–0000–000000000000",
    webId: "00000000–0000–0000–0000–000000000000",
    listId: "00000000–0000–0000–0000–000000000000"
  }),
  success:function(data){
    console.log("Rejoice, for now you can use REST",data);
  }
});
  • Thank you for this. I will try and see if this works on-premises and to bind to a drop down list. – Doug Clelland Dec 28 '18 at 18:20

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.