0
votes

I'm trying to write a javascript on CRM Phone Call page. We have a custom look-up field called new_department, and we want to automatically populate the field with value "IT" (there should be one) when the form is opened.

The thing is we have a separate Dev and Production CRM link therefore I cannot just assign a hard-coded GUID value into this field. So first I wrote a Rest Retrieve Multiple to get the correct department.

Then my problem is I'm not sure about the result returned from this Retrieve Multiple. How do I grab just the GUID from Rest? I'm seeing that this is a type of {Object}. Then lastly how do I go about setting the lookup value after retrieving the {Object}? Any help is greatly appreciated.

Here is my code.

function phonecall() {
var formType = Xrm.Page.ui.getFormType();
if (formType == 1) //create
{
    //RetrieveMultiple function
    var DepartmentId = getITDepartment();

    //set the lookup value
    var ID = DepartmentId.id;
    var departmentValue = new Array();
    departmentValue[0] = new Object();
    departmentValue[0].id = DepartmentId;
    departmentValue[0].name = 'IT';
    userValue[0].entityType = "new_department";        
    Xrm.Page.getAttribute("new_department").setValue(departmentValue);
}
}

function getITDepartment()
{
XrmServiceToolkit.Rest.RetrieveMultiple("new_departmentSet", "$select=new_departmentId&$filter=new_name eq 'IT'",
   function (results) {
       if (results.length > 0)
           resultList = results;
   }, function (error) { alert(error); }, function onComplete() { }, false);
return resultList;
}

Thanks much.

2

2 Answers

2
votes

I'm not familiar with XrmServiceToolkit but here how code could look like to work properly - I replaced only assigning part:

var DepartmentId = getITDepartment();

if (DepartmentId != null && DepartmentId.length > 0){
    Xrm.Page.getAttribute("new_department").setValue([{
    id: DepartmentId[0].new_departmentId,
    name: "IT",
    entityType: "new_department"
    }]);
}
1
votes

You are setting the lookup value correctly, you just need to get the Id correctly. The results variable is an array of new_department records, so try something like this:

var resultId = null;
XrmServiceToolkit.Rest.RetrieveMultiple("new_departmentSet", "$select=new_departmentId&$filter=new_name eq 'IT'",
   function (results) {
       if (results.length > 0)
           resultId = results[0].new_departmentId; //gets the first record's Id
   }, function (error) { alert(error); }, function onComplete() { }, false);
return resultId;