Wednesday, August 13, 2008

Convert Text Field to Picklist

The Code uses a simpe trick which takes the text field id , assigns it to a new picklist field and deletes it from the form, when the crmForm is saved the picklist is recognized as a valid attribute and its data is sent to the server "for safe keeping...".

function CrmPageOnLoad() {
ConvertTextToPickList( "[ControlId]");

function ConvertTextToPickList( controlId ) {
//Referance the Text field
var textControl = document.getElementById( controlId );
//Create a new Picklist (SELECT) control
var picklistControl = document.createElement( "SELECT" );
//Copy the Text field properties to the picklist =;
picklistControl.req = textControl.req;
//Set Required Style
picklistControl.className = "ms-crm-SelectBox "; //"selectBox " v3.0
AddPickListValues( picklistControl );
//load the picklist selected value from the text field (saved) datavalue
picklistControl.value = textControl.DataValue;
//append the picklist to the document
textControl.parentElement.appendChild( picklistControl );
//remove the text field , we don't need it anymore.
textControl.parentElement.removeChild( textControl );

function AddPickListValues( picklistControl ) {
var picklistValues = GetPickListValues();
for( var i = 0 ; i < picklistValues.length; i++ )
//Create a new Option
var option = document.createElement( "OPTION" );
//In this case the value and text are the same
option.value = option.innerText = picklistValues[i];
//Add the option to the picklist
picklistControl.appendChild( option );

function GetPickListValue() {
//This is just a stub , you can load the values from the server as well
return [ 'A' , 'B' , 'C' ];



Anonymous said...

This looks very cool...unfortunately I'm new to CRM development and am a little unsure on how to implement this in the OnLoad event on my form in CRM 3.0.
I tried just putting the function call and the 3 other functions into the OnLoad() event function but that doesn't seem to work... I'm getting an object required error which means I could just have a syntax issue. But debugging this JS crap is such a pain. If everything that gets entered into the event form is stuffed inside a function call... how can it contain functions? That's where I'm getting confused.

Adi Katz said...

The first thing you need to do is to change the text control id to match the id on your crmForm.
Other then that I suggest you enable debugging and see exactly where the code breaks.


Anonymous said...

Thanks for the help.
I did find type-o in the sample.
The sample code executes

The function is actually named GetPickListValue();