5

I am trying to get a collection of terms under a term set so I can see which have custom properties. I have been searching for almost a week now and keep coming up with nothing. I found several example pieces of code as to how to retrieve them but every time I try to run

var context = SP.ClientContext.get_current();

//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);

//Term Stores
var termStores = taxSession.get_termStores();

context.load(taxSession);
context.load(termStores);


context.executeQueryAsync(function () {
    var storeEnum = termStores.getEnumerator();

}, function (sender, args) {

    console.log(args.get_message());

});

It bombs on the getEnumerator with the error Uncaught Error: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

I have loaded SP.Taxonomy.js, Sp.Runtime.js directly in my custom MasterPage.

1
  • my issue ended up being SP.js was not being loaded and would time out. Commented Mar 30, 2015 at 13:50

2 Answers 2

3

I am using below code for past year or so

SP.SOD.executeOrDelayUntilScriptLoaded(Function.createDelegate(this, function() {
    'use strict';

    var taxonomySodLoaded = false;

    if (typeof(_v_dictSod) !== 'undefined' &&
        _v_dictSod['sp.taxonomy.js'] == null) {
        SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
    }
    else {
        taxonomySodLoaded = _v_dictSod['sp.taxonomy.js'].state === Sods.loaded;
    }

    if (taxonomySodLoaded) {
        loadTaxonomy();
    }
    else {
        SP.SOD.executeFunc('sp.taxonomy.js', false, Function.createDelegate(this, loadTaxonomy));
    }
}), 'core.js');

loadTaxonomy = function() {
    var context = SP.ClientContext.get_current();
    var taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
    var termStore = taxonomySession.get_termStores();
    context.load(termStore, 'Include(Name, Parent, IsRoot, LocalCustomProperties)');
    context.executeQueryAsync(Function.createDelegate(this, function(sender, args) {
        //success
    }), Function.createDelegate(this, function(sender, args) {
        //failed
    }));
};
1

if you need to find all terms in you termset that have a custom proepty, you can use this method: SP.Taxonomy.TermSet.getTermsWithCustomProperty(c)

https://msdn.microsoft.com/en-us/library/office/dn312633.aspx

Another Solution:

Based on: https://gist.github.com/zplume/1395dee6b8b2e38e5927

Basically, you call it as YOURNAMESPACE.Taxonomy.Helper.Function.getTerms(CURRENTSITEURL,GROUPNAME)

and it returns JS Object with all terms, including custom properties.

(function () {
var nsName = "YOURNAMESPACE"; // root namespace name
window.Rise = window.Rise || {};
var ns = window[nsName];
ns.Taxonomy = ns.Taxonomy || {};

ns.Taxonomy.Helper = {
    Data: {
        Sites: {} // cache for Taxonomy terms JSON
    },
    // get metadata terms for a term group, in the context of the specified site collection
    Function: {
        Sites: {}, // JSOM cache for Taxonomy objects
        getTerms: function (url, groupName) {
            var ctx,
                siteData = ns.Taxonomy.Helper.Data.Sites[url] || {},
                siteObjects = ns.Taxonomy.Helper.Function.Sites[url] || {};

            function getTermGroups() {
                ctx = new SP.ClientContext(url);

                // Cache TaxonomySession as a global variable to avoid uninitialized error when making multiple requests against the term store (i.e. when querying more than one group)
                siteObjects.taxonomySession = siteObjects.taxonomySession || SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);
                siteObjects.termGroups = siteObjects.taxonomySession.getDefaultSiteCollectionTermStore().get_groups();
                ctx.load(siteObjects.termGroups);
                return ns.Taxonomy.Helper.executeQuery(ctx, siteObjects.termGroups, true);
            }

            function getTermGroup(termGroups) {
                siteObjects.termGroups = termGroups;
                siteObjects.termGroup = jQuery.grep(siteObjects.termGroups, function (value, index) {
                    return value.get_name() == groupName;
                })[0];
                if (siteObjects.termGroup) {
                    ctx.load(siteObjects.termGroup);
                    return ns.Taxonomy.Helper.executeQuery(ctx);
                } else {
                    return jQuery.Deferred().reject("No Group by name '" + groupName + "' was found.").promise(); // don't continue the promise chain
                }
            }

            function getTermSets() {
                siteData.TermGroups = siteData.TermGroups || {};
                siteData.TermGroups[groupName] = {};
                siteObjects.termSets = siteObjects.termGroup.get_termSets();
                ctx.load(siteObjects.termSets);
                return ns.Taxonomy.Helper.executeQuery(ctx, siteObjects.termSets, true);
            }

            function getAllTerms(termSets) {
                siteObjects.termSets = termSets;
                siteData.TermGroups[groupName].TermSets = siteData.TermGroups[groupName].TermSets || {};
                var termSetsPromises = jQuery.map(siteObjects.termSets, function (termSet, i) {
                    return getTermsForTermSet(termSet); // load term set terms async
                });
                return jQuery.when.apply(jQuery, termSetsPromises) // when all terms are loaded
                    .then(function () {
                        ns.Taxonomy.Helper.Data.Sites[url] = siteData;
                        ns.Taxonomy.Helper.Function.Sites[url] = siteObjects;
                        return siteData;
                    })
                    .done(function () {
                        return siteData;
                    });
            }

            function getTermsForTermSet(termSet, termSetsPromises) {
                var termSetName = termSet.get_name();
                siteData.TermGroups[groupName].TermSets[termSetName] = {};
                siteData.TermGroups[groupName].TermSets[termSetName].Terms = siteData.TermGroups[groupName].TermSets[termSetName].Terms || [];
                siteData.TermGroups[groupName].TermSets[termSetName].Props = termSet.get_customProperties();
                var terms = termSet.get_terms(),
                    termsGlobal = siteData.TermGroups[groupName].TermSets[termSetName].Terms;
                return getTermsRecursive(terms, termsGlobal);
            }

            function getTermsRecursive(terms, termsGlobal) {
                // populate global variable with terms and child terms recursively
                ctx.load(terms);
                return ns.Taxonomy.Helper.executeQuery(ctx)
                    .then(function () {
                        return getTerms(terms, termsGlobal);
                    });
            }

            function getTerms(terms, termsGlobal) {
                terms = ns.Taxonomy.Helper.enumerableToArray(terms);

                var childTermsPromises = jQuery.map(terms, function (term, i) {
                    var termName = term.get_name();

                    var arrayTerm = {};
                    arrayTerm.Label = termName;
                    arrayTerm.TermGuid = term.get_id().toString();
                    arrayTerm.prop = term.get_localCustomProperties();

                    var url = term.get_localCustomProperties()._Sys_Nav_SimpleLinkUrl;

                    if (term.get_localCustomProperties().css)
                        arrayTerm.css = term.get_localCustomProperties().css;

                    if (Rise.Helper.isItemEmpty(url)) {
                        arrayTerm.isUrl = false;
                    } else {
                        arrayTerm.isUrl = true;
                    }

                    arrayTerm.Url = url;
                    termsGlobal.push(arrayTerm);

                    arrayTerm.Terms = arrayTerm.Terms || [];

                    // get child terms
                    return term.get_termsCount() > 0 ? (function () {
                        return getTermsRecursive(term.get_terms(), arrayTerm.Terms);
                    })() : null;
                });
                return jQuery.when.apply(jQuery, childTermsPromises);
            }

            return getTermGroups()
                .then(getTermGroup)
                .then(getTermSets)
                .then(getAllTerms);
        }
    },
    enumerableToArray: function (enumerable) {
        var enumerator = enumerable.getEnumerator();
        var array = [];
        while (enumerator.moveNext()) {
            var current = enumerator.get_current();
            array.push(current);
        }
        return array;
    },
    executeQuery: function (ctx, returnObject, toArray) {
        var def = new jQuery.Deferred();
        ctx.executeQueryAsync(function () {
            returnObject ?
                toArray ?
                def.resolve(ns.Taxonomy.Helper.enumerableToArray(returnObject)) : // resolve returnObject as an array
                def.resolve(returnObject) : // resolve returnObject
                def.resolve(); // resolve undefined
        }, function (sender, args) {
            console.log(args);
            def.reject(args);
        });
        return def.promise();                
    }
};
})();
3
  • Rise.Helper.isItemEmpty(url) is not defined so it causes an error.
    – Rothrock
    Commented Jul 19, 2016 at 21:00
  • Rise.Helper.isItemEmpty() is just a helper function that checked if item is null, undefined etc. You can substitute for you own.
    – dotsa
    Commented Jul 20, 2016 at 21:55
  • Thank you That is what it seemed to be and that is what I did. This is an amazing bit of code and I think it could be very useful, but it is overkill for the problem I'm trying to solve. Would you happen to have an answer or suggestions for my taxonomy issue? sharepoint.stackexchange.com/questions/187096/…
    – Rothrock
    Commented Jul 21, 2016 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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