Tuesday, February 9, 2010

CRM - Dynamic Picklists Using Arrays

For this example, I have a picklist Status and another Reason Code for that status. This code is very easy to maintain assuming some of the values in either the status or reason code changes in the future. This code is very easy to transform into your own environment. Simply change the values listed in red.

/********************************************************************/
/* status and reason code dynamic picklists
/********************************************************************/
var REASON_CODE_VALUES = new Array();
var REASON_CODE_COMPLETE_LIST = new Object();
var STATUS_ELEMENT = document.getElementById('new_status');
var REASON_CODE_ELEMENT = document.getElementById('new_reasoncode');

//REASON_CODE_VALUES['status picklist names'] = [reason code picklist values];
REASON_CODE_VALUES['Approved'] = [47,31,32,70,69,33,34,35,36,37,38,30,54];
REASON_CODE_VALUES['Delayed'] = [39,40,75,73,72,41,57,42,43,58,45,46,61,59,74,60,8,50,14,12,15,49,11,6,9,13,10,4];
REASON_CODE_VALUES['Denied'] = [67,76,19,18,68,21,20,22,53,24,17];
REASON_CODE_VALUES['Incomplete'] = [62,26,63,25,65,29,28,27];

// Store the complete set of values for the pick lists and wire up events
if (REASON_CODE_ELEMENT)
{
REASON_CODE_COMPLETE_LIST = REASON_CODE_ELEMENT.Options;
}
if (STATUS_ELEMENT)
{
STATUS_ELEMENT.onchange = OnStatusChange;
STATUS_ELEMENT.FireOnChange();
}

function OnStatusChange()
{
if (STATUS_ELEMENT && STATUS_ELEMENT.SelectedText && REASON_CODE_ELEMENT)
{
SetupReasonCodeValuesFor(STATUS_ELEMENT.SelectedText);
}
else
{
RemoveAllItemsFrom(REASON_CODE_ELEMENT);
REASON_CODE_ELEMENT.DataValue = null;
}
}

// Clears all the pick list items from the specified element
function RemoveAllItemsFrom(element)
{
if (element)
{
for (var i = element.Options.length - 1; i > 0; i--)
{
element.DeleteOption(parseInt(i));
}
}
}


// Returns true if the passed in array contains the value
function ArrayContains(array, value)
{
var result = false;
if (array && value)
{
for (var i = 0; i < result =" true;" currentvalue =" REASON_CODE_ELEMENT.DataValue;" options =" REASON_CODE_COMPLETE_LIST;" reasoncodevalues =" REASON_CODE_VALUES[StatusType];" i =" REASON_CODE_ELEMENT.Options.length"> 0; i--)
{
if (!ArrayContains(ReasonCodeValues, i))
{
REASON_CODE_ELEMENT.DeleteOption(parseInt(i));
}
}
}
else
{
RemoveAllItemsFrom(REASON_CODE_ELEMENT);
}
// Set the current value back into the element
REASON_CODE_ELEMENT.DataValue = currentValue;
}

No comments:

Post a Comment