Pages

Friday, 11 April 2008

Join CRM Field Values Into A Single Field

It's time for some JavaScript fun today. :)

Something I get asked for occasionally is to join a few CRM form field values into a single field. A possible example for this would be the joining of the first name and last name fields into the full name field on a contact form. This can, of course, be done by using a callout or plug-in (and to a limited extent, by using a workflow rule) but the easiest way to get this done is by using a form script.

I took the time and created a generic script that (I hope) covers all possible cases and irregularities in the data. Explanations are built into the script itself as remarks.


//Declare your world.
var strings = new Array();
var target = crmForm.all.some_nvarchar_field;

//A function that check whether there is a legitimate value further on.
function checkNext(a,i) {
if (i >= a.length) {
return false;
} else if (a[i] != null && a[i] != "") {
return true;
}
else {
return checkNext(a,i+1);
}
}

//A function that add a line to an array
function addLine(l,t) {
//If lookup field.
if (t == 1) {
if (l.DataValue) {
return l.DataValue[0].name;
} else {
return null;
}
//If text field.
} else if (t == 2) {
return l.DataValue;
//If picklist field.
} else if (t == 3) {
return l.SelectedText;
} else {
return null;
}
}

//Add each of the values in order to the array.
//As the second parameter, enter 1 for lookup fields, 2 for any text field and 3 for picklist fields.
strings[0] = addLine(crmForm.all.some_lookup_field,1);
strings[1] = addLine(crmForm.all.some_nvarchar_field,2);
strings[2] = addLine(crmForm.all.some_picklist_field,3);

//Loop through the array and chain its
values.
for (i=0;i<strings.length;i++) {
if (strings[i] != null && strings[i] != "" && checkNext(strings,i+1)) {
if (i==0){
target.DataValue = strings[i] + " - ";
} else {
target.DataValue += strings[i] + " - ";
}
} else if (strings[i] != null && strings[i]
!= "") {
if (i==0) {
target.DataValue = strings[i];
} else
{
target.DataValue += strings[i];
}
}
}


It seems there isn't much I can do about how badly the script comes out on the blog...
My apologies. I'll take it up with Google.

No comments: