get/set lookup value in CRM 4

 
/* Jscript */


// get lookup
gLookupGetValue = function (objLookup){
/*
This function is used read a value from lookup field
This function requires the following parameters:
objLookup: reference to the lookup object e.g. crmForm.all.productid
Returns: Array
[0] = returns lookup GUID
[1] = returns lookup text value
[2] = returns lookup entity type name (e.g. account)
[3] =//returns lookup entity type code (e.g. 1=account), 2=contact, etc)
Example:
var name = gLookupGetValue(crmForm.all.accountid)[1]
Author: GP
*/

var lookupItem = new Array;
var arr = new Array();
arr[0] = ""; //returns lookup GUID
arr[1] = ""; //returns lookup text value
arr[2] = ""; //returns lookup entity type name (e.g. account)
arr[3] = ""; //returns lookup entity type code (e.g. 1=account), 2=contact, etc)
// Get a reference to the lookup control on the form.
lookupItem = objLookup.DataValue;

// If there is data in the field, show it in a series of alerts.
if (lookupItem != null){
// Return the GUID of the lookup.
arr[0] = lookupItem[0].id;
// Return the text value of the lookup.
arr[1] = lookupItem[0].name;

// Return the entity type name of the lookup.
arr[2] = lookupItem[0].typename;

// Return the entity type code of the lookup.
arr[3] = lookupItem[0].type;
}
return arr;
}
// set lookup
gLookupSetValue= function(objID, objText, objType){
/*
This function is used set a defaultvalue in a lookup field and requires the following parameters:
objID: ID of the record
objText: Text or Name of the record
objType: Entity code or Entity Name
Returns: lookup object
Designed by: Geron Profet
Example 1: retrieve based on entity type code
var defaultpricelevelname = 'Standard';
var defaultpricelevelid = gGetValue('pricelevelid','pricelevel','name',defaultpricelevelname)[2];
crmForm.all.pricelevelid.DataValue = gLookupSetValue(defaultpricelevelid, defaultpricelevelname, 1022);

Example 2: retrieve based on entity type name
crmForm.all.pricelevelid.DataValue = gLookupSetValue(defaultpricelevelid, defaultpricelevelname, 'pricelevel');
*/

// Create a lookupItem to store the values that you want to set to a target lookup control.
var lookupData = new Array();
var lookupItem= new Object();

//Set the id, name and typecode or typename properties to the object.
lookupItem.id = objID;
lookupItem.name = objText;

//if objType is not numeric, assume the entitytypename is passed
if (!isNaN(objType)){
lookupItem.type = objType;
} else {
lookupItem.typename = objType;
}

// Add the object to the array and return the lookupItem that you just created.
lookupData[0] = lookupItem;
return lookupData;
}