Quantcast
Channel: SharePoint Development Lab by @avishnyakov » js
Viewing all articles
Browse latest Browse all 13

Leveraging SPClientAutoFill control in SharePoint 2013 – build your own auto complete experience!

$
0
0

070713_0434_LeveragingS3.png
Have you even seen a new people picker control in SharePoint 2013? It has been improved, it can be reused on your pages, and it has a cool auto-complete functionality. The fantastic news is that you also may reuse the auto-complete part of people picker to enable auto complete for your text boxes or other controls. It has to do with SPClientAutoFill control so let’s build something cool!

What is it all about?

Take a look on people picker in SharePoint 2013. It has auto complete feature and looks like this:

Basically, auto complete feature it is served by “_layouts/15/autofill.debug.js” file and JavaScript control called “SPClientAutoFill”. Do you want to leverage the same auto complete for you own controls? Let’s rock, then!

Leveraging SPClientAutoFill control

Setting up look and feel

To get started, let’s make a simple markup to setup an input element and some necessary stuff for SPClientAutoFill. The simplest html markup might look like this:

<style>
	.client-autoFillContainer {
		z-index: 1;
		padding: 0px;
		display: none;
		cursor: default;
		max-width: 300px;
		min-width: 300px;
		position: absolute;
		border-color: rgb(198, 198, 198);
	}
</style>

<script src='http://tesla-dev42/sites/dev4/Style Library/spdevlab/spdevlab.auto.js'></script>

<table>
	<tr>
		 <td>Country:</td>
		 <td>
			<div style='position: relative;'>
		    	<input type='text' id='clientName' />
		   		 <div class='sp-peoplepicker-autoFillContainer client-autoFillContainer' id='clientAutoCompleteValues'></div>
			</div>
		</td>
	<tr>
</tr>
</table>

<script>
	(function() {
		ExecuteOrDelayUntilScriptLoaded(function() {
			RegisterSod("autofill.js", "/_layouts/15/autofill.debug.js");

			ExecuteOrDelayUntilScriptLoaded(function() {

				var autoContriesInput = new spdevlab.demo.autofill.AutoCountries();

				autoContriesInput.init("clientName", "clientAutoCompleteValues");

			}, "autofill.js");

			LoadSodByKey("autofill.js");
		}, 'sp.js');
	})();
</script>

For the sample, I would use “Content Editor” web part to push html markup on the page. Surely, you may change all this for your own needs. The markup is quite simple, however there are a few things to be mentioned. First of all, this is the most crucial piece of the markup to get auto complete setup well:

<div style='position: relative;'>
	<input type='text' id='clientName' />
	<div class='sp-peoplepicker-autoFillContainer client-autoFillContainer' id='clientAutoCompleteValues'></div>
</div>

Next, the whole container has to have “relative” positioning. This helps SPClientAutoFill sets a correct positioning for the auto fill area. You may get more insight about that with reverse engineering the default people picker control html markup.

Finally, some additional styling is required. I got a few classes such as “sp-peoplepicker-autoFillContainer client-autoFillContainer” which were gained form the default people picker controls. Again, you may customize them later to adjust the look and feel to you needs.

This is a preliminary setting which could produce the same UI as people picker has.

Setting up JavaScript

The JavaScript object model for SPClientAutoFill control is quite simple.

The big picture is that you have SPClientAutoFill javascript class. It requires two id to be provided as well as “populate” callback to fill the auto complete variables. You also have different settings such as “AutoFillMinTextLength” or “VisibleItemCount” and the rest.

Finally, there is a bunch of the methods to work with the instance of the current SPClientAutoFill control. I use “PopulateAutoFill” methods in the sample, however there are lots of them to be explored.

Okay, here is a demo to get started. I use “Countries javascript array” to populate countries suggestions in the country input as you type the first letters. No magic at all, quite enjoyable to get started, I suppose.

Type.registerNamespace('spdevlab.demo.autofill.AutoCountries');

spdevlab.demo.autofill.AutoCountries = function () {

    var self = this;

    // static
    spdevlab.demo.autofill.AutoCountries._countries = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Anguilla", "Antigua & Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas"
		, "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia & Herzegovina", "Botswana", "Brazil", "British Virgin Islands"
		, "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Cape Verde", "Cayman Islands", "Chad", "Chile", "China", "Colombia", "Congo", "Cook Islands", "Costa Rica"
		, "Cote D Ivoire", "Croatia", "Cruise Ship", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea"
		, "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Polynesia", "French West Indies", "Gabon", "Gambia", "Georgia", "Germany", "Ghana"
		, "Gibraltar", "Greece", "Greenland", "Grenada", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India"
		, "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kuwait", "Kyrgyz Republic", "Laos", "Latvia"
		, "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Mauritania"
		, "Mauritius", "Mexico", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Namibia", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia"
		, "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Oman", "Pakistan", "Palestine", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal"
		, "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Rwanda", "Saint Pierre & Miquelon", "Samoa", "San Marino", "Satellite", "Saudi Arabia", "Senegal", "Serbia", "Seychelles"
		, "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "South Africa", "South Korea", "Spain", "Sri Lanka", "St Kitts & Nevis", "St Lucia", "St Vincent", "St. Lucia", "Sudan"
		, "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor L'Este", "Togo", "Tonga", "Trinidad & Tobago", "Tunisia"
		, "Turkey", "Turkmenistan", "Turks & Caicos", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "Uruguay", "Uzbekistan", "Venezuela", "Vietnam", "Virgin Islands (US)"
		, "Yemen", "Zambia", "Zimbabwe"];

    // private
    spdevlab.demo.autofill.AutoCountries.prototype._targetInput = null;
    spdevlab.demo.autofill.AutoCountries.prototype._autofillControl = null;

    // public
    spdevlab.demo.autofill.AutoCountries.prototype.init = function (targetInputId, targetAutoCompleteId) {

        self._targetInput = document.getElementById(targetInputId);
        self._autofillControl = new SPClientAutoFill(targetInputId, targetAutoCompleteId, self._onPopulate);

        self._autofillControl.AutoFillMinTextLength = 2;
        self._autofillControl.VisibleItemCount = 15;
    };

    // private
    spdevlab.demo.autofill.AutoCountries.prototype._buildOptionItem = function (name, id) {

        var item = {};

        item[SPClientAutoFill.KeyProperty] = id;
        item[SPClientAutoFill.DisplayTextProperty] = name;
        item[SPClientAutoFill.TitleTextProperty] = name;
        item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option;

        return item;
    }

    spdevlab.demo.autofill.AutoCountries.prototype._buildSeparatorItem = function () {

        var item = {};

        item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator;

        return item;
    }

    spdevlab.demo.autofill.AutoCountries.prototype._buildFooterItem = function (title) {

        var item = {};

        item[SPClientAutoFill.DisplayTextProperty] = title;
        item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer;

        return item;
    }

    spdevlab.demo.autofill.AutoCountries.prototype._onPopulate = function (targetElement) {

        var value = targetElement.value.toLowerCase();
        var countries = spdevlab.demo.autofill.AutoCountries._countries;

        var items = [];
        var totalItems = 0;

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

            var lCountryName = countries[i].toLowerCase();

            if (lCountryName.indexOf(value) == 0) {
                items.push(self._buildOptionItem(countries[i], i));
                totalItems++;
            }
        }

        items.push(self._buildSeparatorItem());

        if (totalItems == 0)
            items.push(self._buildFooterItem("No results. Please refine your query."));
        else
            items.push(self._buildFooterItem("Found " + totalItems + " items!"));

        self._autofillControl.PopulateAutoFill(items, self._onSelectItem);
    }

    spdevlab.demo.autofill.AutoCountries.prototype._onSelectItem = function (targetInputId, item) {

        var targetElement = document.getElementById(targetInputId);
        targetElement.value = item[SPClientAutoFill.DisplayTextProperty];
    }
};

At the end, you may get auto suggestions like that:

Doesn’t it look impressive, does it? I think it does. Just with a few lines of JavaScript code you may get significant improvements of your application look and feel.

What’s next?

I’m planning to add a few fields with auto-complete features to SharePoint 2013 custom field samples at codeplex. This is my playground project for different fields with client side customizations. Stay tuned, more fields are to come.

Files

Conclusion

SharePoint 2013 has a lot of client side improvements. JavaScript object model is quite large and yet to be explored. I recently wrote about mQuery and some interesting things about “Quick Edit” mode for the custom fields. Well, that’s just the top of the iceberg.

On the other hand, you may utilize and reuse some of the JavaScript features or components right now. SPClientAutoFill control is an excellent sample of that, and more are to come. Stay tuned!


Viewing all articles
Browse latest Browse all 13

Trending Articles