Convert Lookup field to token input with JSLink

4

May 5, 2014 by Ravi C Khambhati

If you do know know what is JSLink jump to the end of the article for the references and if you do lets get started.

So with this post I will demonstrate how we can convert Lookup field to token input. To do this I have used below jQuery plugin.

http://loopj.com/jquery-tokeninput/

This plugin has lot of options which you can explore based on your requirement.

Step 1: Create “Employee Title” list with entries
JSLink 01

Step 2: Create “Employee” list with lookup column to “Employee Title”
JSLink 02

Step 3: Create JSLink file
Create js file with below content and place under 15 hive.

var lookupFieldName = "EmployeeTitleLookup";
var lookupFieldTitle = "Employee Title Lookup";

var lookupListTitle = "Employee Title";
var lookupListFieldName = "EmployeeTitle";
var lookupValueSeperator = ";#";

(function () {
    var employeeTitleFiledContext = {};
    employeeTitleFiledContext.Templates = {};
    employeeTitleFiledContext.Templates.Fields = {
        "EmployeeTitleLookup": {
            "NewForm": employeeTitleFiledTokenTemplate,
            "EditForm": employeeTitleFiledTokenTemplate
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(employeeTitleFiledContext);
    
})();

function employeeTitleFiledTokenTemplate(ctx) {
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
    var fieldName = formCtx.fieldName;
    var fieldTitle = formCtx.fieldSchema.Title
    var fieldValue = formCtx.fieldValue

    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        var selectedValue = null;
        var selectedItems = $("#" + formCtx.fieldName).tokenInput("get");
        $.each(selectedItems, function (index, selectedItem) {
            if (selectedValue === null) {
                selectedValue = selectedItem.id + lookupValueSeperator + selectedItem.name;
            }
            else {
                selectedValue = selectedValue + lookupValueSeperator + selectedItem.id + lookupValueSeperator + selectedItem.name;
            }
        });
        document.getElementById(fieldName).value = selectedValue;
        return document.getElementById(fieldName).value;
    });

    formCtx.registerInitCallback(formCtx.fieldName, function () {
        initControl(lookupListTitle, lookupListFieldName);
    });

    var html = "<span dir=\"none\">" +
                    "<input id=\"" + fieldName + "\" " +
                        "class=\"ms-long ms-spellcheck-true\" " +
                        "title=\"" + fieldTitle + "\" " +
                        "maxLength=\"255\" " +
                        "value=\"" + fieldValue + "\" " +
                        "type=\"text\">" +
                "</span>";
    return html;
}

function initControl(listTitle, fieldName) {
    getListItem(_spPageContextInfo.webAbsoluteUrl, listTitle, fieldName);
}

function getListItem(url, listname, fieldName) {
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            getListItem_Complete(data, lookupFieldName);
        },
        error: function (data) {
            getListItem_Failure(data, lookupFieldName);
        }
    });
}

function getListItem_Complete(data, fieldName) {
    var jobTitles = [];

    jobTitles = $.map(data.d.results, function (item, i) {
        return {
            id: item.Id,
            name: item.JobTitle
        };
    });

    var itemValue;
    var itemText;
    var existingValue = $("#" + fieldName).val();

    if (existingValue === null || existingValue === "" || existingValue === undefined) {
        $("#" + fieldName).tokenInput(jobTitles, {
            theme: "facebook",
            tokenDelimiter: ";#",
            preventDuplicates: true,
        });
    }
    else {

        existingValue = existingValue.split(";#");
        var existingValues = new Array();
        $.each(existingValue, function (index, jobTitle) {
            if (index % 2 === 1) {
                itemText = jobTitle;
                existingValues.push(
                    { id: itemValue, name: itemText }
                );
            }
            else {
                itemValue = jobTitle;
            }
        });
        
        $("#" + fieldName).tokenInput(jobTitles, {
            theme: "facebook",
            prePopulate: existingValues,
            tokenDelimiter: ";#",
            preventDuplicates: true,
        });
    }
}

function getListItem_Failure(data) {
    console.log(data.statusText);
    console.log(data.responseText);
}

Step 3: Create HTML file
This file will have all reference of required javascript and jquery. Copy this file to 15 Hive.
You can reference this in master page as well. For this demo I am placing under Content Editor web part which is shown in next step.

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<link href="http://loopj.com/jquery-tokeninput/styles/token-input.css" rel="stylesheet"/>
<link href="http://loopj.com/jquery-tokeninput/styles/token-input-facebook.css" rel="stylesheet"/>
<script src="http://loopj.com/jquery-tokeninput/src/jquery.tokeninput.js"></script>

Step 5: Add Content editor web part
Navigate and edit Add new page, with new “Content Editor web part” web part as shown in below image. Perform the same step on Edit page as well.
JSLink 03

Update Content link with the file created in previous step. for e.g. “~site/_layouts/15/JSLink/JSLink.html”

JSLink 06

Step 6: Edit Employee WebPart property
Update JSLink webpart property with the the file created in Step 2. for e.g. “~site/_layouts/15/JSLink/LookupToAutocomplete.js”

JSLink 05

Step 7: Demo
JSLink 04

Please share your comments, suggestions, inputs

Happy Coding 🙂

References
http://code.msdn.microsoft.com/office/Client-side-rendering-JS-2ed3538a
http://www.codeproject.com/Articles/524962/JSLink-Custom-JS-Rendering-in-SharePoint

Advertisements

4 thoughts on “Convert Lookup field to token input with JSLink

  1. Chirag says:

    Nice Article Ravi and very well demonstrated. Thanks

  2. Jayashri Thorat says:

    Hi Ravi, Nice article. Is it possible with the lookup field, where data of that of that field is exceeding threshold limit.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: