Cascading field in SharePoint

By July 25, 2016 blog No Comments

My friends, who also work in SharePoint area, have a lot of requests to accumulate of experience and sometime apply to reality scenarios. That would be fine for me to review the coding skill somehow. By the way, in this article, I can only support three methods to have a cascading field in SharePoint with easiest deploying, understanding and configuring to run its functioning.

1. Cascading relationship
Imaging that we have a field for Country and a field for Province. Each country has many provinces and when we select a country, only provinces belong to that country can be available to show in the dropdown list.
To prepare the data to input the value, I create 3 lists: Country, Province and Customers. For province list, I create a lookup field named “Country” to look-up to Country list. I also create a lookup field named Country and a lookup field named Province for Customers.

1

The requirement is to create new customer, in the dropdown of Province, it shows only the province of following selected country.

22. Cascading display control

Just think about the situation when we need to show or hide a control when we do action on another control. In this example, I just implement to show or hide control when we check for the field.

3

3. Cascading active control
It’s very simple and similar to the case 2nd. Instead of hidden control, this case just do disable or enable another control in the form.

4

 

Let’s Started
Okay, from my friends, I always think about the easiest way to deploy the solution or easy to use. Sometime, there are some limitations when we do customize the page layout, css, html or even of coding by using JSOM. However, let try your best in implementing to match the requirement as much as possible.
Before to show the code, I must explain on how to configure the variable for each of cascading type. You will see in the code the declaration of 3 variables, like this:
HBX.ProviderField_InternalName = “FIELD_1″;
HBX.ReceiverField_InternalName = “FIELD_2″;
HBX.ActionType = “Cascading”;
where:

  • HBX.ProviderField_InternalName is a source field and do some actions then send the behavior to another field
  • HBX.ReceiverField_InternalName is a target field and receive a behavior from the source field
  • HBX.ActionType is a type of cascading. There are 3 values upon to 3 cases above, that is Cascading, Display and Active.

This code must be applied to both the NewForm and EditForm, but I just show the way to deploy on the NewForm.

  1. Open the new form (newform.aspx). Click on Site Settings -> Edit Page
  2. Click Add a web part. In the web part galleries, select the ScriptEditor web part from Media & Content category.
  3. Click on Edit Snippet
  4. Copy and paste this code to the form, then click Save the page from the Ribbon. (see the code at the end of this article)

Customization
In some cases, you can customize the code depend on your situation and update the code. I love to use js to implement anything on SharePoint and restrain to use the farm solution with the backend code to implement your feature. With me, as simple as possible!

<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js”></script>
<script type=”text/javascript”>
var HBX = HBX || {}

HBX.ProviderField_InternalName = “No_x0020_Province_x003f_”;
HBX.ReceiverField_InternalName = “Province”;
HBX.ActionType = “Display”; //Cascading;Display;Active
HBX.ProviderObject = null;
HBX.ReceiverObject = null;
HBX.ReceiverFieldObject = null;
HBX.ProviderFieldObject = null;
HBX.ListId = _spPageContextInfo.pageListId;
HBX.Items = [];

HBX.Query = function() {
“use strict”;

var deferred = $.Deferred(),
execute = function() {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getById(HBX.ListId);

HBX.ReceiverFieldObject = list.get_fields().getByInternalNameOrTitle(HBX.ReceiverField_InternalName);
HBX.ProviderFieldObject = list.get_fields().getByInternalNameOrTitle(HBX.ProviderField_InternalName);
ctx.load(HBX.ReceiverFieldObject);
ctx.load(HBX.ProviderFieldObject);
ctx.executeQueryAsync(onSuccess, onError);
return deferred;
},
onSuccess = function() {
deferred.resolve();
},
onError = function(sender, args) {
HBX.err = args;
deferred.reject(args);
};

return {
execute: execute
}
}

HBX.FetchData = function() {
“use strict”;

var errorMessage = function (args) {
alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}

var resetList = function() {
HBX.Items = [ { ID: 0, Title: ‘(None)’ } ];
$(HBX.ReceiverObject).empty();
}

var resetListChoice = function() {
HBX.Items = [];
$(HBX.ReceiverObject).empty();
}

var execute = function(selectedValue) {
var webPromise = new HBX.Query().execute();
webPromise.promise();
webPromise.then(
function() {
var typeAsString = HBX.ReceiverFieldObject.get_typeAsString();
switch(typeAsString) {
case “Lookup”:
resetList();
var fieldLKId = HBX.ReceiverFieldObject.$2_0.$K_0.LookupField;
var listLKId = HBX.ReceiverFieldObject.$2_0.$K_0.LookupList;
var ctx = SP.ClientContext.get_current();
var listLK = ctx.get_web().get_lists().getById(listLKId);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(“<View><Query><Where><Eq><FieldRef Name='” + HBX.ProviderField_InternalName + “‘/><Value Type=’Lookup’ LookupId=’TRUE’>” + selectedValue + “</Value></Eq></Where></Query></View>”);
var listItemLK = listLK.getItems(camlQuery);
ctx.load(listItemLK, “Include(Id, Title)”);
ctx.executeQueryAsync(function(e, a) {

var listEnumerator = listItemLK.getEnumerator();
while (listEnumerator.moveNext()) {
var currentItem = listEnumerator.get_current();
var lkItem = { ID: currentItem.get_id(), Title: currentItem.get_item(“Title”) };
HBX.Items.push(lkItem);
}

$.each(HBX.Items, function (index, item) {
$(HBX.ReceiverObject).append($(‘<option></option>’).val(item.ID).html(item.Title));
});
}, errorMessage);
break;
case “Choice”:
resetListChoice();
HBX.Items = HBX.ReceiverFieldObject.$2_0.$K_0.Choices;
if (parseInt(selectedValue) >= 0 && parseInt(selectedValue) <= 4)
{
//From 1 – 4 people: The seats < 1500
$.each(HBX.Items, function (index, item) {
if (parseInt(item) < 1500)
{
$(HBX.ReceiverObject).append($(‘<option></option>’).val(item).html(item));
}
});
}
else if (parseInt(selectedValue) > 4 && parseInt(selectedValue) <= 7)
{
//From 5 – 7 people: The seats < 3000
$.each(HBX.Items, function (index, item) {
if (parseInt(item) > 1500 && parseInt(item) < 3000)
{
$(HBX.ReceiverObject).append($(‘<option></option>’).val(item).html(item));
}
});
}
else {
//From >= 8 people: The seats > 3000
$.each(HBX.Items, function (index, item) {
if (parseInt(item) > 3000)
{
$(HBX.ReceiverObject).append($(‘<option></option>’).val(item).html(item));
}
});
}
break;
default:
break;
}
}, errorMessage);
}

return {
execute: execute
}
}

$(document).ready(function() {
SP.SOD.executeFunc(‘SP.Runtime.js’, ‘SP.Runtime’, function () {
ExecuteOrDelayUntilScriptLoaded(function() {

switch(HBX.ActionType)
{
case “Cascading”:
HBX.ProviderObject = $(“SELECT[Title='” + HBX.ProviderField_InternalName + “‘]”);
HBX.ReceiverObject = $(“SELECT[Title='” + HBX.ReceiverField_InternalName + “‘]”);

HBX.ReceiverObject.empty();
HBX.ProviderObject.change(function() {
var xc = new HBX.FetchData();
xc.execute($(HBX.ProviderObject).find(“option:selected”).text());

});

HBX.ProviderObject.ready(function() {
var xc = new HBX.FetchData();
xc.execute($(HBX.ProviderObject).find(“option:selected”).text());
});
break;
case “Display”:
HBX.ProviderObject = $(“[Title='” + HBX.ProviderField_InternalName + “‘]”);
HBX.ReceiverObject = $(“[Title='” + HBX.ReceiverField_InternalName + “‘]”);

HBX.ProviderObject.change(function() {
if ($(this).is(‘:checked’))
{
$(HBX.ReceiverObject).parent().parent().parent().show();
}
else
{
$(HBX.ReceiverObject).parent().parent().parent().hide();
}
});

HBX.ProviderObject.ready(function() {if ($(this).is(‘:checked’))
{
$(HBX.ReceiverObject).parent().parent().parent().show();
}
else
{
$(HBX.ReceiverObject).parent().parent().parent().hide();
}});
break;
case “Active”:
HBX.ProviderObject = $(“[id^='” + HBX.ProviderField_InternalName + “‘]”);
HBX.ReceiverObject = $(“[id^='” + HBX.ReceiverField_InternalName + “‘]”);

HBX.ProviderObject.change(function() {
if ($(this).is(‘:checked’))
{
$(HBX.ReceiverObject).removeAttr(“disabled”);
}
else
{
$(HBX.ReceiverObject).attr(“disabled”, “disabled”);
}
});

HBX.ProviderObject.ready(function() {if ($(this).is(‘:checked’))
{
$(HBX.ReceiverObject).removeAttr(“disabled”);
}
else
{
$(HBX.ReceiverObject).attr(“disabled”, “disabled”);
}});
break;
default:
break;
}

}, “sp.js”); });
});
</script>

Leave a Reply