Friday, March 2, 2012

Getting related record from a lookup and displaying it as a link in CRM 2011 with OData/JSON

Lookups provide a way to associate a record with a related value. The simplest example is showing the primary contact in the account form. Keeping with this example, what if I want a record in the primary contact to show up in the account form, and be able to open up the record form on clicking the field?

The business case I am going to focus on deals with showing the primary contacts preferred service in the accounts form. I am thus able to view the service record without having to open up the contact form and click on the service lookup.

Clicking on the name of the preferred service will open up the service record in a new window.
This provides the ability to show a detail that is 2 layers deep,  and can be adapted to suit other cases as well.

Here are the steps to get this going:

1. Create a new text field called Contact's Preferred Service and add it to the accounts form.



























2. Create a webresource of type script and add the following script to it. Replace the value "new_contactspreferredservice" in the script with the name of the text field.



//get the service id from the contact

function getContactservice() {
    var lookUpObjectValue = Xrm.Page.getAttribute("primarycontactid").getValue();
    if ((lookUpObjectValue != null)) {
        var lookuptextvalue = lookUpObjectValue[0].name;

        var lookupid = lookUpObjectValue[0].id;
        //alert(lookupid);


        var serverUrl = Xrm.Page.context.getServerUrl();

        //The XRM OData end-point
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";


        var odataSetName = "ContactSet";

        var odataSelect = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + lookupid + "')";

        //alert(odataSelect);

        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function(XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function(data, textStatus, XmlHttpRequest) {

                var result_contact = data.d;

                var service_id = result_contact.PreferredServiceId.Id;
  
  //if service_id exists, display the text field, attach the onlick event and change the style to looks like  

 a web address

                if (service_id != null) {
                    
                    document.getElementById("new_contactspreferredservice_c").style.display = 'block';
                    document.getElementById("new_contactspreferredservice_d").style.display = 'block';
                    
                    Xrm.Page.getAttribute("new_contactspreferredservice").setValue(result_contact.PreferredServiceId.Name);

                    crmForm.all["new_contactspreferredservice"].style.cursor = "hand";

                    crmForm.all["new_contactspreferredservice"].style.color = "blue";

                    crmForm.all["new_contactspreferredservice"].style.textDecoration = "underline";

                    crmForm.all["new_contactspreferredservice"].onclick = function() { clickfn1(service_id); };

                }

  //if service_id does not exist, hide the text field

                else if (service_id == null) {
                    
                    Xrm.Page.getAttribute("new_contactspreferredservice").setValue("");
                    document.getElementById("new_contactspreferredservice_c").style.display = 'none';
                    document.getElementById("new_contactspreferredservice_d").style.display = 'none';

                }


            },
            error: function(XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
        });

    }

} 

//open the service url
function clickfn1(id) {

    var serverUrl = Xrm.Page.context.getServerUrl();

    //alert(serverUrl);



    url1 = serverUrl + "/main.aspx?etc=4001&pagetype=entityrecord&id=%7B" + id + "%7D";

    window.open(url1, "_blank", "height=600,width=800,modal=yes");

}



Let me walk through the script a bit here. The function getContactservice() is called during the onChange of the primary contact lookup. The details of the json/ odata call have been explained in a previous post of mine. If the contact has an associated Preferred service, the text field new_contactspreferredservice is updated to the service name. I have made some style changes to make it look like a clickable url.

If the contact does not have a service selected, the new_contactspreferredservice field is hidden in the form.

3. Save and publish the changes.

This is what the completed account form looks like.





















Clicking on the link for field Contact's Preferred Service opens up the service details in a new window.




















If there is no Service associated with the contact, the Contacts Preferred Service field is hidden to the user.


















Remember to register the function on the onload of the form too. That way existing Primary Contacts with Service records show up as an url link.

No comments:

Post a Comment