0

I'm trying to get the terms from sharepoint online and put them into a select tag using JavaScript.

My terms are set up like I have main categories and each of them have sub categories.

For example

-Entertainment

---TV

---Games

---Music

So I loop through the main categories and get the id for each of them. Then inside that loop I try to get the sub categories for each main id.

The result is that it only succeed to get the sub categories from the last main id and fails on first. By the order on my console.log messages in console my guess is that it has to do with the async query. But how can I work my way around this?

 function loadTerms() {
        var appContext = new SP.ClientContext.get_current();
        var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(appContext);
            //Term Store under which to create the term.
            var termStore = taxSession.getDefaultSiteCollectionTermStore();
            //Pass ID of the Meetings Term Set
            var termSet = termStore.getTermSet("275d8d26-a608-4fdd-b9bf-1e3ab3c350c4");
            var terms = termSet.get_terms();
            appContext.load(terms);
            appContext.executeQueryAsync(function () {
                var termEnumerator = terms.getEnumerator();
                while (termEnumerator.moveNext()) {
                    let currentTerm = termEnumerator.get_current();

                    console.log(currentTerm.get_name());
                    console.log(currentTerm.get_id());


                    var termSetParent = termStore.getTerm(currentTerm.get_id());
                    var termSetGroupTerms = termSetParent.get_terms();
                    appContext.load(termSetGroupTerms);
                    appContext.executeQueryAsync(function () {
                            var termGroupEnum = termSetGroupTerms.getEnumerator();
                            while (termGroupEnum.moveNext()) {
                                console.log(termGroupEnum.get_current().get_name());
                            }
                        }, function (sender, args) {
                            console.log(args.get_message());
                        });


                }
            }, function (sender, args) {
                console.log(args.get_message());
            });
        }
0

The following code for your reference.

<script type="text/javascript">
/*!
 * Termset utilities
 */
var Hcf = Hcf || {};
Hcf.Util = Hcf.Util || {};
Hcf.Util.Termset = Hcf.Util.Termset || {};
(function(module) {
    /**
     * Returns a termset, based on ID
     *
     * @param {string} id - Termset ID
     * @param {object} callback - Callback function to call upon completion and pass termset into
     */
    module.getTermSet = function (id, callback) {
        SP.SOD.loadMultiple(['sp.js'], function () {
            // Make sure taxonomy library is registered
            SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
            SP.SOD.loadMultiple(['sp.taxonomy.js'], function () {
                var ctx = SP.ClientContext.get_current(),
                    taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx),
                    termStore = taxonomySession.getDefaultSiteCollectionTermStore(),
                    termSet = termStore.getTermSet(id),
                    terms = termSet.getAllTerms();
                ctx.load(terms);
                ctx.executeQueryAsync(Function.createDelegate(this, function (sender, args) {
                    callback(terms);
                }),
                Function.createDelegate(this, function (sender, args) { }));
            });
        });
    };

    /**
     * Returns an array object of terms as a tree
     *
     * @param {string} id - Termset ID
     * @param {object} callback - Callback function to call upon completion and pass termset into
     */
    module.getTermSetAsTree = function (id, callback) {
        module.getTermSet(id, function (terms) {
            var termsEnumerator = terms.getEnumerator(),
                tree = {
                    term: terms,
                    children: []
                };
            // Loop through each term
            while (termsEnumerator.moveNext()) {
                var currentTerm = termsEnumerator.get_current();
                var currentTermPath = currentTerm.get_pathOfTerm().split(';');
                var children = tree.children;
                // Loop through each part of the path
                for (var i = 0; i < currentTermPath.length; i++) {
                    var foundNode = false;
                    for (var j = 0; j < children.length; j++) {
                        if (children[j].name === currentTermPath[i]) {
                            foundNode = true;
                            break;
                        }
                    }
                    // Select the node, otherwise create a new one
                    var term = foundNode ? children[j] : { name: currentTermPath[i], children: [] };
                    // If we're a child element, add the term properties
                    if (i === currentTermPath.length - 1) {
                        term.term = currentTerm;
                        term.title = currentTerm.get_name();
                        term.guid = currentTerm.get_id().toString();
                    }
                    // If the node did exist, let's look there next iteration
                    if (foundNode) {
                        children = term.children;
                    }
                    // If the segment of path does not exist, create it
                    else {
                        children.push(term);
                        // Reset the children pointer to add there next iteration
                        if (i !== currentTermPath.length - 1) {
                            children = term.children;
                        }
                    }
                }
            }
            tree = module.sortTermsFromTree(tree);
            callback(tree);
        });
    };

    /**
     * Sort children array of a term tree by a sort order
     *
     * @param {obj} tree The term tree
     * @return {obj} A sorted term tree
     */
    module.sortTermsFromTree = function (tree) {
        // Check to see if the get_customSortOrder function is defined. If the term is actually a term collection,
        // there is nothing to sort.
        if (tree.children.length && tree.term.get_customSortOrder) {
            var sortOrder = null;
            if (tree.term.get_customSortOrder()) {
                sortOrder = tree.term.get_customSortOrder();
            }
            // If not null, the custom sort order is a string of GUIDs, delimited by a :
            if (sortOrder) {
                sortOrder = sortOrder.split(':');
                tree.children.sort(function (a, b) {
                    var indexA = sortOrder.indexOf(a.guid);
                    var indexB = sortOrder.indexOf(b.guid);
                    if (indexA > indexB) {
                        return 1;
                    } else if (indexA < indexB) {
                        return -1;
                    }
                    return 0;
                });
            }
            // If null, terms are just sorted alphabetically
            else {
                tree.children.sort(function (a, b) {
                    if (a.title > b.title) {
                        return 1;
                    } else if (a.title < b.title) {
                        return -1;
                    }
                    return 0;
                });
            }
        }
        for (var i = 0; i < tree.children.length; i++) {
            tree.children[i] = module.sortTermsFromTree(tree.children[i]);
        }
        return tree;
    };
})(Hcf.Util.Termset);

var termSetId="275d8d26-a608-4fdd-b9bf-1e3ab3c350c4";
(function (module) {
    // Recursively loop through the termset and create list items
    function renderTerm(term) {
        var html = '<li>' + term.title + '';
        if (term.children && term.children.length) {
            html += '<ul>';
            for (var i = 0; i < term.children.length; i++) {
                html += renderTerm(term.children[i]);
            }
            html += '</ul>';
        }
        return html + '</li>';
    }
    module.getTermSetAsTree(termSetId, function (terms) {
        var html = '';
        // Kick off the term rendering
        for (var i = 0; i < terms.children.length; i++) {
            html += renderTerm(terms.children[i]);
        }
        var list = document.getElementById('metadata');
        list.innerHTML = html;
       // $('#metadata').html("<ul>"+html+"</ul>");
    });
})(Hcf.Util.Termset);

</script>
<ul id="metadata"/>

Reference: Returning a SharePoint 2013 termset in a tree structure using JavaScript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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