Link to home
Start Free TrialLog in
Avatar of apollo7
apollo7Flag for United States of America

asked on

CRM 2011 Lookup and populating related fields

Hi

I discovered a problem with using the fullname, emailaddress1, address1_telephone1 to populate values in my SSRS report.  I need to use the custom lookup field (i.e. CobSalesManager) that pulls from User and then pull in the email and phone for the User selected in the lookup

[This will then provide the User that I select as the CobSalesManager for my SSRS report and the email/phone number associated with the user selected].

I need the javascript to read the Lookup value of CobSalesManager and then add the related email/phone fields for the selected CobSaleManager user.

I have created relationships between the CobSalesManager lookup and the email/phone text fields.   I now need code for the onchange event of the CobSalesManager field to populate the related text fields for email/phone

Thanks
Avatar of Rikin Shah
Rikin Shah
Flag of India image

Hi,

Have you tried any code yet? What is the relationship between both?
Avatar of apollo7

ASKER

There is code all over for this function, so I picked the first one and I am starting there, open to better approaches.  The relationships are N:1 between User and Quote fields that I have mapped for fields on the Quote form that come from user.

[Note: this is very old code, uses crm.form instead of xrm.page - it has been a long time since I worked with CRM 2011, generally work with CRM 2013, CRM 2015 and xrm code.]


GetValues();
function GetValues()
 {
            if(crmForm.all.csc_cobhamsalesmanager.DataValue!=null)
            {
            FetchID =crmForm.all.csc_cobhamsalesmanager.DataValue[0].id ;
            var authenticationHeader = GenerateAuthenticationHeader();
            //Prepare the SOAP message.
            var xml = "<?xml version='1.0' encoding='utf-8'?>" +
                                 "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
                                 " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
                                 " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"; + authenticationHeader +
                            "<soap:Body>" +
                            "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
                            "<entityName>" + EntityName + "</entityName>" +
                            "<id>" + FetchID + "</id>" +
                            "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
                            "<q1:Attributes>";
            //configure attribute list You can add attribute list
                  xml = xml + '<q1:Attribute>' +FirstAttribute + '</q1:Attribute>';
                  xml = xml + '<q1:Attribute>' +SecondAttribute + '</q1:Attribute>';
                  xml = xml + '<q1:Attribute>' +ThirdAttribute + '</q1:Attribute>';
            
            xml = xml + '</q1:Attributes></columnSet>';
            xml = xml + "</Retrieve></soap:Body></soap:Envelope>";
            //call function to create Soap Request to ms crm webservice
             xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
            xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
            xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
            xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
            xmlHttpRequest.send(xml);
            resultXml = xmlHttpRequest.responseXML;
            //Check for error
            errorCount = resultXml.selectNodes('//error').length;
                    if (errorCount != 0) { //log error
                        
                        msg = resultXml.selectSingleNode('//description').nodeTypedValue;
                       alert(msg);
                    }
                    else 
                    {
                       if (resultXml.selectSingleNode('//q1:FirstAttribute') != null) {
                            crmForm.all.FirstAttribute.DataValue = resultXml.selectSingleNode('//q1:FirstAttribute').attributes[0].nodeTypedValue;
                        }
                        if (resultXml.selectSingleNode('//q1:SecondAttribute') != null) {
                            crmForm.all.SecondAttribute.DataValue = resultXml.selectSingleNode('//q1:SecondAttribute').attributes[0].nodeTypedValue;
                        }
                        if (resultXml.selectSingleNode('//q1:ThirdAttribute') != null) {
                            crmForm.all.ThirdAttribute.DataValue = resultXml.selectSingleNode('//q1:ThirdAttribute').attributes[0].nodeTypedValue;
                        }
                      }

            }
     }

Open in new window

Avatar of apollo7

ASKER

Change of plans, decided to go with odata, downloaded the oData Designer, working on query string for User.  I have my organization.svc from Developer Resources, just need the syntax to retrieve from the User entity
Hi,

I would suggest you stick with Soap or Organization service. Sooner or later you will have to move your code to CRM 2016 where OrganizationData service is deprecated. The code will still run but again in further it will be unsupported for sure and your code will break for sure.

Microsoft has introduced a new WebAPI to deal with OData with some more advantages.

I would suggest you use XrmServiceToolkit.js. check here-https://xrmservicetoolkit.codeplex.com
The documentation is self explanatory.
Avatar of apollo7

ASKER

Thanks, will download the toolkit
Avatar of apollo7

ASKER

I have the JS - xrmservicetoolkit loaded as a Web Resource.    I opened the text and copied the js into Visual Studio 2010 including the references.

It has 2965 lines of code and comments, can you point me to a section that I would use to create an onChange event for my CobSalesManager lookup to pull in the related email and phone number from the User entity?

Thanks
Avatar of apollo7

ASKER

Is this a good place to start?

//Fire the OnChange event for the mapped fields
            // so that the lookup dialog are changed with the filtered view for the current values.
            for (var customFilterView in jQueryXrmCustomFilterView.config) {
                var target = jQueryXrmCustomFilterView.config[customFilterView].target;
                var entityName = jQueryXrmCustomFilterView.config[customFilterView].entityName;
                var viewName = jQueryXrmCustomFilterView.config[customFilterView].viewName;
                var dynamic = jQueryXrmCustomFilterView.config[customFilterView].dynamic;
                var fetchXml = jQueryXrmCustomFilterView.config[customFilterView].fetchXml;
                var layoutXml = jQueryXrmCustomFilterView.config[customFilterView].layoutXml;

Open in new window

Hi,

You can create a fetchXml and use it with required parameters to execute it. Or use simple retrieve function to get a single record. Its upon your requirements.

From the above code for CRM 4.0, I think the most suitable code would be this. Here is an example-

var cols = ["firstname", "lastname", "middlename", "familystatuscode", "ownerid", "creditlimit", "birthdate", "donotemail", "donotphone"];
var retrievedContact = XrmServiceToolkit.Soap.Retrieve("contact", contactId, cols); //synchronous call
var familyStatusLable = retrievedContact.attributes['familystatuscode'].formattedValue;
var firstName = retrievedContact.attributes['firstname'].value;

Open in new window

Avatar of apollo7

ASKER

Ok, here is a piece of code that looks like it would what I want.  So to do what I want to do, I would change the case statements in switch (calltype).  I have added what I think the changes need to be, please advise

function Lookup_Changed(attributeName, entityName, callbackId, columns) {
    var lookup = Xrm.Page.data.entity.attributes.get(attributeName).getValue();
    if (lookup===null) {
        return false;
    }
  
    if (lookup[0].id == null) { 
        return false;
    }
	
	XrmServiceToolkit.Rest.Retrieve(
        lookup[0].id,
        entityName,
        columns,
		null,
        function (result) {
            retrieveReqCallBack(callbackId, result);
        },
        function (error) {
            throw error;
        },
		true
    );
}

function retrieveReqCallBack(calltype, data) {
    var toLookup=function(data) {
        if (data==null || data=="" || (data.Id==null)) {
            return null;
        }
    
        var result=new Array();
        result[0] = {};
        result[0].id = data.Id;
        result[0].name = data.Name;
        result[0].entityType = data.LogicalName;
        return result;
    }

    switch (calltype) {
        case 'cobsalesmanagerlookup':
            Xrm.Page.data.entity.attributes.get("csc_cobhamsalesmanager").setValue(toLookup(data.csc_cobhamsalesmanager));
            break;
        case 'userlookup':
            Xrm.Page.data.entity.attributes.get("csc_cobhamsalesmanphone").setValue(data.Telephone1);
            break;
        default:
            break;
    }
    }

Open in new window

Yes, please go ahead with it.
Avatar of apollo7

ASKER

I added the following .js as csc_quotelookup to webresources and then called the Lookup_Changed  function from the onChange event.

The lookup is just locked and there is an "error on page" in the lower left corner of the Quote form.

function Lookup_Changed(attributeName, entityName, callbackId, columns) {
    var lookup = Xrm.Page.data.entity.attributes.get(attributeName).getValue();
    if (lookup===null) {
        return false;
    }
  
    if (lookup[0].id == null) { 
        return false;
    }
	
	XrmServiceToolkit.Rest.Retrieve(
        lookup[0].id,
        entityName,
        columns,
		null,
        function (result) {
            retrieveReqCallBack(callbackId, result);
        },
        function (error) {
            throw error;
        },
		true
    );
}

function retrieveReqCallBack(calltype, data) {
    var toLookup=function(data) {
        if (data==null || data=="" || (data.Id==null)) {
            return null;
        }
    
        var result=new Array();
        result[0] = {};
        result[0].id = data.Id;
        result[0].name = data.Name;
        result[0].entityType = data.LogicalName;
        return result;
    }

    switch (calltype) {
        case 'cobsalesmanagerlookup':
            Xrm.Page.data.entity.attributes.get("csc_cobhamsalesmanager").setValue(toLookup(data.csc_cobhamsalesmanager));
            break;
        case 'userlookup':
            Xrm.Page.data.entity.attributes.get("csc_cobhamsalesmanphone").setValue(data.Telephone1);
            break;
        default:
            break;
    }
    }

Open in new window

Avatar of apollo7

ASKER

Hi

I got the onChange for the csc_cobhamsalesmanager to work, however, I received the error below.

Things to investigate in the code above?

User generated image
Avatar of apollo7

ASKER

\_00_/  i dunno

I am wondering if there is a no-code way to select a user in CRM 2011, get the value of that user's address1_telephone1 source field and write it to a custom field on the quote?

I have tried many code variations but so far no luck.  The following code looks perfect but does not work so I must be missing something

function getCobhamDetail() {

    var cobhamId = Xrm.Page.data.entity.attributes.get("systemuserid").getValue();   //write your lookup schema name
    if (cobhamId != null) {
        var cols = ["telephone1", "emailaddress1"];  // Write your attributes

        var retrievedCobham = CrmServiceToolkit.Retrieve("owner", ownerId, cols);

        var telephone1 = Xrm.Page.data.entity.attributes.get("address1_telephone`");
        csc_cobhamsalesmanphone.setValue(retrievedCobham.getValue(telephone1));


    }

}

Open in new window

This js code is in the Quote Form LIbrary as a web resource and on the onChange Event Handler that selects the owner that needs to write the address1_telephone1 value to the custom csc_cobhamsalesmanphone field
Hi,

If you're using XrmServiceToolkit, then you should use following statement:

var retrievedCobham = XrmServiceToolkit.Soap.Retrieve("owner", ownerId, cols);
instead of-
var retrievedCobham = CrmServiceToolkit.Retrieve("owner", ownerId, cols);

CrmServiceToolkit was made for CRM 4.0
Avatar of apollo7

ASKER

Thanks, we have both loaded (this was an upgrade from 4.0), I made the change to XrmServiceToolKit.

I am getting the 'Error:  Unable to get property 'getvalue' of undefined or null reference'

I put in some alerts and tried two syntax methods for systemuserid (lookup)

Only get to the alert("1"), then get the above error


// onChange CobsalesManager

function getCobhamDetail() {

    alert("1");
    var cobhamId = Xrm.Page.data.entity.attributes.get("systemuserid").getValue()[0].id; //lookup schema name 
   //var cobhamId = Xrm.Page.data.entity.attributes.get("systemuserid").getValue(); //lookup schema name 
  alert(systemuserid);

    if (cobhamId != null) {
        var cols = ["telephone1", "emailaddress1"];  // Write your attributes

        var retrievedCobham = XrmServiceToolkit.Soap.Retrieve("owner", ownerId, cols);
        var telephone1 = Xrm.Page.data.entity.attributes.get("address1_telephone");
        
        alert("2");
        csc_cobhamsalesmanphone.setValue(retrievedCobham.getValue(telephone1));
    }

}

Open in new window

Hi,

I do not think there is an error with the written statement. Perhaps, you want to check the logical attribute name for the user id. I think that will need some correction.

Also, I suspect there is an "owner" entity available. You will need to correct entity logical name as well.
var retrievedCobham = XrmServiceToolkit.Soap.Retrieve("owner", ownerId, cols);
Avatar of apollo7

ASKER

Hi

I am down to alert (3) and getting the error below. I have included the code


User generated image
// onChange CobsalesManager 

function getCobhamDetail() {

    alert("1");
    var cobhamId = Xrm.Page.data.entity.attributes.get("ownerid").getValue()[0].id;   //write your lookup schema name
    alert("2");
    alert(cobhamId);


    if (cobhamId != null) {
        var cols = ["telephone1", "emailaddress1"];  // Write your attributes

        alert("3");
        var retrievedCobham = XrmServiceToolkit.Soap.Retrieve("owner", ownerid, cols);
        var telephone1 = Xrm.Page.data.entity.attributes.get("address1_telephone");
        
        alert("4");
        csc_cobhamsalesmanphone.setValue(retrievedCobham.getValue(telephone1));
    }

}

Open in new window

Avatar of apollo7

ASKER

Recent development, I tried taking the ()[0].id off the end of getvalue for ownerid (which was returning a guid in alert(cobhamId);

Now the alert(cobhamId) is returning [object Object], I have seen this before, have to look up what it means
ASKER CERTIFIED SOLUTION
Avatar of Rikin Shah
Rikin Shah
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of apollo7

ASKER

The new fields that I am trying to populate are for SSRS reports that I am modifying.  

I have not made any tangible movement forward from debugging the code.  

The idea was to get the value of the csc_cobhamsalesmananger lookup and then pull in the related email address and telephone number of the User in the lookup to populate values on the Quote form (which would then appear on a report).

I am now working on using the SSRS code to populate the email and telephone fields related to the User in the lookup.  The User already appears on the report as it appears in the lookup on the form.

Any advice?

Thanks
Hi,

This is too confusing... You're writing a JS code for SSRS?!? I am not getting this.
Avatar of apollo7

ASKER

My requirements were to add the CobhamSalesManager (user) lookup to the form and also display the CobhamSalesManager selectedd on a SSRS report on the form

I have added the CobhamSalesManager lookup to the quote form (user lookup) and can show  the CobhamSalesManager selected on the SSRS report, as well

This User selected as CobhamSalesManager displays correctly on the Quote form and on the SSRS report

I decided it would be easier to write the related email and telephone to the Quote form when the CobhamSalesManager was selected

When I tried to add the CobhamSalesManager's email and telephone to the form and  the report

Once the CobhamSalesManager (user) is selected on the form and the report is executed from the form, it shows the user selected as CobhamSalesManager  but displays the tester's email and telephone on  the Quote form and the SSRS report
Hi,

Most probably the issue here is you're referring to the wrong user id. I think you're referring to System User Id instead of the owner of the record.
If that is not the case, can you post whole code and let us know where does it goes wrong?
Avatar of apollo7

ASKER

Yes, that sounds like a plan, I will try ownerid as the source of the CobhamSalesManager lookup (with the related email and telephone field from owner)
Avatar of apollo7

ASKER

When I create a Lookup for the CobhamSalesManager, my options for a lookup field do not include owner or owner.  My options are account, contact, user - I have been selecting User because the person that would be a Cobham Sales Manager is a CRM user.

What am I missing in terms of using ownerid instead of systemuserid?

ThanksUser generated image
Avatar of apollo7

ASKER

I have made no progress trying to get the right user id.  How do I refer to the record owner, instead of the System User Id

My problem is that I dont see a way to create a Lookup on the record owner that users can select as the Cobham Sales Manager

Need help.

Thanks
hi, you don't need to create separate lookup... each record in crm will have an owner

just search owner lookup on the form and refer that lookup to your code.
Avatar of apollo7

ASKER

Thanks -  the trick here is that I have to get around a requirement that the person creating the quote can select the Cobham Sales Manager from a lookup (for each quote)

If the ownerid is the Cobham Sales Manager for each quote (by default), is there a way I can autofill the Cobham Sales Manager field with code?

Also, would this allow me to grab the owner's internalemailaddress and address1_telephone1 to fill two custom fields on the Quote form?
Avatar of apollo7

ASKER

Thanks, this was the best advice and enjoyed working with you on it.