Welcome!

Industrial IoT Authors: Dalibor Siroky, Liz McMillan, William Schmarzo, Elizabeth White, Stackify Blog

Blog Feed Post

SharePoint 2013 Autocomplete textboxes using the term store and CSOM

I wanted to create an autocomplete textbox in a SharePoint app recently by using terms from the term store.  Since retrieving items from the term store can be a bit involved I wanted to show you the steps involved.  This solution make use of jQuery UI Autocomplete.  The code loads the terms from the term store and then sets the source.  This implementation is really only ideal for a small amount of terms, but it’s enough to get you started.

For this example, I am going to use a simple set of terms using state names in the United States.  My terms are included in a group named Classification and a Term Set named States.  Here is what my term store looks like.

TermStoreStates

In this example, we’re going to build our code inside a Client Web Part.  Take a look at that post if you are not familiar with the process yet.  We then need to add a heap of JavaScript references.  Some of these are included already, but specifically we need to load SP.Taxonomy.js.  We also need to include init.js as I mentioned in an earlier blog post.

<script type="text/javascript" src="../Scripts/jquery-1.7.1.min.js"></script>

<script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>

<script type="text/javascript" src="/_layouts/15/init.js"></script>

<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>

<script type="text/javascript" src="/_layouts/15/sp.js"></script>

<script type="text/javascript" src="/_layouts/15/sp.taxonomy.js"></script>

My web part is called AutocompleteWebPart.aspx so I am going to add a JavaScript file for my code called AutocompleteWebPart.js.  We also need to include a reference to jQuery UI  You’ll need to download this and include it in your project or pull it from a CDN.

<script type="text/javascript" src="../Scripts/AutocompleteWebPart.js"></script>

<script type="text/javascript" src="../Scripts/jquery-ui-1.9.1.custom.min.js"></script>

Lastly to use jQuery UI, you need to include it’s CSS file in the Content folder of your project.

<link rel="Stylesheet" type="text/css" href="../Content/jquery-ui-1.8.22.custom.css" />

Now, I am just going to add a textbox to the body of our page.

<body>

    <div>

        <input id="autocompleteTextBox" type="text" />

    </div>

</body>

The process for querying terms is involved.  You first need to get a reference to the Taxonomy Session, followed by the Group, the Term Set, and finally you can iterate the terms.  There are a lot of good examples out there but many of them take short cuts by using GUIDs for values for things like the group and term set.  This works but is absolutely useless when you are writing proper code that can be deployed to any environment.  You need to be able to reference these items by name, but unfortunately the API makes accessing anything in the term store by name difficult.  It’s not impossible though, it just requires extra code and iteration.  Let’s walk through our JavaScript example below with absolutely no hard-coded GUIDs.

We’ll start by adding some global variables.  We’ll populate these as we go.

var context;

 

var session;

var termStore;

var groups;

var termSets;

var termsArray = [];

We’ll start in a document ready function.  We use the standard code to get a reference to the current context.  We’ll need this to create a new TaxonomySession object.  We then session.GetDefaultSiteCollectionTermStore() to get the default term store.  From there, we need to context.load on the session and termStore objects.  We then use a typical executeQueryAsync method to execute our query.  The onTaxonomySession method will handle success and we’ll use a shared onTaxonomyFailed method to handle any failures.

$(document).ready(

    function () {

        context = new SP.ClientContext.get_current();

 

        session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);

        termStore = session.getDefaultSiteCollectionTermStore();

        context.load(session);

        context.load(termStore);

        context.executeQueryAsync(onTaxonomySession, onTaxonomyFailed);

    });

Just like with the managed API, you must configure your Managed Metadata Service Application Client appropriately in order for the default term store call to work.  Click on the Managed Metadata Service Connection and then click Properties.  Now, make sure the checkbox next to This service application is the default storage location for column specific term sets is checked.  Once, you have made this change your code should work.

ManagedMetadataServiceDefaultChecked

The onTaxonomySession method then retrieves a list of groups.  We have to retrieve all groups because there isn’t a method to just retrieve one by name.  Although there is a method to retrieve a group by id.  Since we don’t want to hard code any GUIDs though.  We have to retrieve all groups and iterate them to find the one we want.  A successful query will call onGroupsLoaded.

function onTaxonomySession() {

    groups = termStore.get_groups();

    context.load(groups);

    context.executeQueryAsync(onGroupsLoaded, onTaxonomyFailed);

}

In this method we have a list of the groups so we need to iterate through them and find the one we want.  In this case, Classification.  The code isn’t ideal but it works.  We start by getting an enumerator with getEnumerator().  We then use this enumerator to examine the groups.  In our loop, we use get_current() to get currentGroup.  We then use get_name() to compare against the one we want.  When a match is found, we call another method getTermSets and pass the term set.

function onGroupsLoaded() {

    // iterate termStores

    var groupEnumerator = groups.getEnumerator();

 

    while (groupEnumerator.moveNext()) {

        var currentGroup = groupEnumerator.get_current();

        if (currentGroup.get_name() == 'Classification')

            getTermSets(currentGroup);

    }

}

In the getTermSets method, we call get_termSets.

function getTermSets(currentGroup) {

    termSets = currentGroup.get_termSets();

    context.load(termSets);

    context.executeQueryAsync(onTermSetsLoaded, onTaxonomyFailed);

}

The onTermSetLoaded method will then iterate through the term sets returned and compare by name in the same way.  In this case, we are looking for the term set named States.  When the match is found, we call getTerms().

function onTermSetsLoaded() {

    var termSetEnumerator = termSets.getEnumerator();

 

    while (termSetEnumerator.moveNext()) {

        var currentTermSet = termSetEnumerator.get_current();

        var termSetName = currentTermSet.get_name();

        if (termSetName == 'States')

            getTerms(currentTermSet);

    }

}

This is now the last call we need to make.  This retrieves all of the terms for the term set.  Unfortunately, we have to get all of them (as far as I know) which is why I don’t recommend this with large term sets.

function getTerms(termSet) {

    terms = termSet.get_terms();

    context.load(terms);

    context.executeQueryAsync(onTermsLoaded, onTaxonomyFailed);

}

The onTermsLoaded method will iterate through the terms and add them to an array that the jQuery UI autocomplete method will accept.  There you have it all of the code to get items from a term set without a hard coded GUID.  It’s a lot of code, but not too bad once you get used to it.

Lastly, we’ll get a reference to our textbox and use the .autocomplete() method passing in the value of our array.

function onTermsLoaded() {

    var termsEnumerator = terms.getEnumerator();

 

    while (termsEnumerator.moveNext()) {

        var currentTerm = termsEnumerator.get_current();

        termsArray.push(currentTerm.get_name());

    }

 

    $("#autocompleteTextBox").autocomplete({ source: termsArray });

}

At this point, we are done, but we do need to implement our failure method.

function onTaxonomyFailed(sender, args) {

    alert('Taxonomy Error:' + args.get_message());

}

If you are using this code in an app, the last thing you need to do is set the Taxonomy permission to Read in the AppManifest.xml file.  This will let us query the term store.

AppManifrstTaxonomy

At this point, we can test it.  Deploy your app and add the app part to a page.

AutocompleteExample

So, a little code involved here but the results are great.  You can configure the jQuery autocomplete plugin in a variety of ways too.  This code could probably be optimized some so if you have improvements, let me know.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is a consultant at Hitachi Consulting specializing in SharePoint and Office 365 for clients in the energy sector. He has more than ten years of experience delivering solutions in the energy, travel, advertising and consumer electronics verticals.

Corey specializes in delivering ECM and search solutions to clients using SharePoint. Corey has always focused on rapid adoption of new Microsoft technologies including Visual Studio 2013, Office 365, and SharePoint.

He is a member of the .NET Mafia (www.dotnetmafia.com) where he blogs about the latest technology and SharePoint. He is dedicated to the community and speaks regularly at user groups and SharePoint Saturdays.

@ThingsExpo Stories
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...