Populate Lookup value on selection of another Lookup


 Step 1.


Step 2.

Step 3.

Let me explain the scenario…

Suppose we have City Lookup on Lead entity and we want to populate Region (Lookup), State (Lookup) and Zone (Lookup) on selection of particular City from City Lookup. You need to write below code on OnChange event of City Lookup field.

if(crmForm.all.new_cityid.DataValue !=null)

{

    var citylookupValues = crmForm.all.new_cityid.DataValue;

    if(citylookupValues[0] !=null)

    {

        var cityID = citylookupValues[0].id;

        var regionID = GetAttributeValueFromID(“new_city”, cityID , “new_regionid”);

        var stateID = GetAttributeValueFromID(“new_city”, cityID , “new_stateid”);

        var zoneID = GetAttributeValueFromID(“new_region”, regionID , “new_zoneid”);   

        if(regionID != null)

        {

            //Create an array to set as the DataValue for the lookup control.

            var regionlookupData = new Array();

            //Create an Object add to the array.

            var regionlookupItem= new Object();

            //Set the id, typename, and name properties to the object.

            regionlookupItem.id = regionID;

            regionlookupItem.typename = ‘new_region’;

            regionlookupItem.name = regionName;

            // Add the object to the array.

            regionlookupData[0] = regionlookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_regionid.DataValue = regionlookupData;

            crmForm.all.new_regionid.ForceSubmit = true;

 

        }

        if(stateID != null)

        {

            //Create an array to set as the DataValue for the lookup control.

            var statelookupData = new Array();

            //Create an Object add to the array.

            var statelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

            statelookupItem.id = stateID;

            statelookupItem.typename = ‘new_state’;

            statelookupItem.name = stateName;

            // Add the object to the array.

            statelookupData[0] = statelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_stateid.DataValue = statelookupData;

            crmForm.all.new_stateid.ForceSubmit = true;

        }

        if(zoneID != null)

        {

            var zoneName = GetAttributeValueFromID(“new_zone”, zoneID, “new_name”);

            //Create an array to set as the DataValue for the lookup control.

            var zonelookupData = new Array();

            //Create an Object add to the array.

            var zonelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

            zonelookupItem.id = zoneID;

            zonelookupItem.typename = ‘new_zone’;

            zonelookupItem.name = zoneName;

            // Add the object to the array.

            zonelookupData[0] = zonelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_zoneid.DataValue = zonelookupData;

            crmForm.all.new_zoneid.ForceSubmit = true;

        }

     }

}

else

{

     crmForm.all.new_regionid.DataValue = null;

    crmForm.all.new_stateid.DataValue = null;

    crmForm.all.new_zoneid.DataValue = null;

}

 

function  GetAttributeValueFromID(sEntityName, sGUID, sAttributeName)

{

    /*

    * sEntityName: the name of the CRM entity (account, etc.)

    * whose attribute value wish to look up

    * sGUID: string representation of the unique identifier of the specific object whose attrbuite value we wish to look up

    * sAttributeName – the schema name of the attribute whose value we wish returned

    */

 

    var sXml = “”;

    //var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

    var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP.6.0”);

 

    //var serverurl = “http://10.10.40.50:5555”;

    var serverurl = “”;

 

    //set up the SOAP message

    sXml += “<?xml version=\”1.0\” encoding=\”utf-8\” ?>”;

    sXml += “<soap:Envelope xmlns:soap=\”http://schemas.xmlsoap.org/soap/envelope/\””

    sXml += ” xmlns:xsi=\”http://www.w3.org/2001/XMLSchema-instance\””

    sXml += ” xmlns:xsd=\”http://www.w3.org/2001/XMLSchema\”>”;

    sXml += “<soap:Body>”;

    sXml += “<entityName xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” +

    sEntityName + “</entityName>”;

    sXml += “<id xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” +

    sGUID + “</id>”;

    sXml += “<columnSet xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\””

    sXml += ” xmlns:q=\”http://schemas.microsoft.com/crm/2006/Query\””

    sXml += ” xsi:type=\”q:ColumnSet\”><q:Attributes><q:Attribute>” +

    sAttributeName + “</q:Attribute></q:Attributes></columnSet>”;

    sXml += “</soap:Body>”;

    sXml += “</soap:Envelope>”;

 

    // send the message to the CRM Web service

    oXmlHttp.Open(“POST”, serverurl +

    “/MsCrmServices/2006/CrmService.asmx”,false);

    oXmlHttp.setRequestHeader(“SOAPAction”,

    “http://schemas.microsoft.com/crm/2006/WebServices/Retrieve&#8221;);

    oXmlHttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

    oXmlHttp.setRequestHeader(“Content-Length”, sXml.length);

    oXmlHttp.send(sXml);

 

    // retrieve response and find attribute value

    //var result = oXmlHttp.responseXML.selectSingleNode(“//” + sAttributeName);

    var result = oXmlHttp.responseXML.selectSingleNode(“//*[local-name()=\””+  sAttributeName +”\”]”);

    if (result == null)

    {

    return “”;

    }

    else

    return result.text;

}

Using Update Method of CrmService WebService


// Set up the CRM Service.

CrmAuthenticationToken token = new

CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url

=”http://<servername&gt;:<port>/mscrmservices/2007/crmservice.

asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials =

System.Net.CredentialCache.DefaultCredentials;

// Create the contact object.

contact contact = new contact();

// Set the contact object properties to be updated.

contact.address1_line1 =”34 Market St.”;

// The contactid is a key that references the ID of the

contact to be updated.

contact.contactid = new Key();

// The contactid.Value is the GUID of the record to be

changed.

contact.contactid.Value = new Guid(“4D507FFE-ED25-447B-

80DE-00AE3EB18B84″);

// Update the contact.

service.Update(contact);

Using Create Method of CrmService WebService


// Set up the CRM Service.

CrmAuthenticationToken token = new

CrmAuthenticationToken();

// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();

service.Url

=”http://<servername&gt;:<port>/mscrmservices/2007/crmservice.

asmx”;

service.CrmAuthenticationTokenValue = token;

service.Credentials =

System.Net.CredentialCache.DefaultCredentials;

// Create the column set object that indicates the

properties to be retrieved.

ColumnSet cols = new ColumnSet();

// Set the properties of the column set.

cols.Attributes = new string [] {“fullname”};

// contactGuid is the GUID of the record being retrieved.

Guid contactGuid = new Guid(“4D507FFE-ED25-447B-80DE-

00AE3EB18B84″);

// Retrieve the contact.

// The EntityName indicates the EntityType of the object

being retrieved.

contact contact =

(contact)service.Retrieve(EntityName.contact.ToString(),

contactGuid, cols);

 

Using the CrmDiscoveryService Web Service In CRM4.0: On-Premise


CrmDiscovery service is a global installable level service that allow the caller to determine the correct organization and URL for his/her need.

Below example show how to create and configure CrmDiscoveryService Web Service proxy.

 

// Create and configure the CrmDiscoveryService Web service

proxy.

CrmDiscoveryService discoveryService = new

CrmDiscoveryService();

discoveryService.UseDefaultCredentials = true;

discoveryService.Url

=”http://localhost/MSCRMServices/2007/AD/CrmDiscoveryServic

e.asmx”;

// Retrieve the list of organizations that the logged on

user belongs to.

RetrieveOrganizationsRequest orgRequest = new

RetrieveOrganizationsRequest();

RetrieveOrganizationsResponse orgResponse =

(RetrieveOrganizationsResponse)discoveryService.Execute(org

Request);

// Locate the target organization in the list.

OrganizationDetail orgInfo = null;

foreach (OrganizationDetail orgDetail in

orgResponse.OrganizationDetails)

{

if

(orgDetail.OrganizationName.Equals(“AdventureWorksCycle”))

{

orgInfo = orgDetail;

break;

}

}

// Check whether a matching organization was not found.

if (orgInfo == null)

throw new Exception(“The specified organization was not

found.”);

 

How to Call Web Service from Java Script


Here we will be calling the default helloworld webservice that is already created for us when we open a asp.net webservice project template in Visual Studio.

We’ll just have a textbox(html control) which will display us the Hello World! response returned from the web service.

This is the step we need to follow

1) Create a new ASP.NET WebApplication

2) Put a html textbox control on the form

<input type=”text” id=”info”/>

3) Put this script code in the head section of the aspx page

<script language=”javascript”>

var xmlHttp;

function getMessage()

{

xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);

xmlHttp.open(”post”, “http://localhost/WebService1/Service1.asmx/HelloWorld”, false);

xmlHttp.onreadystatechange=doUpdate;

xmlHttp.send();

return false;

}

function doUpdate()

{

if(xmlHttp.readyState==4)

{

var startTag = “<string xmlns=\”http://tempuri.org/\”>”;

var endTag = “</string>”;

var exch;

var valueStart = 0;

var valueEnd = 0;

valueStart = xmlHttp.responseXML.xml.indexOf(startTag, valueEnd) + startTag.length;

valueEnd = xmlHttp.responseXml.xml.indexOf(endTag, valueEnd+1);

exch = xmlHttp.responseXML.xml.substring(valueStart, valueEnd);

document.forms[0].elements[‘Info’].value=exch;

}

 

</script>

4) Call the getMessage function in the body’s onLoad eventHandler

<BODY onload=”getMessage()”>

5) Run the applicaton. We’ll see the HelloWorld! text in our textbox(’info’)

Now let us understand what is happening inside the javascript code

xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”)

This line of code creates the XMLHttpRequest object. This object sends request to the server and processes the responses from it.

The above code creates the object specific to Internet Explorer( <=6.o).

It is implemented as Active X for IE. However in IE 7 XMLHttpRequest will come as native JavaScript object.

For other browsers we can write

xmlHttp=new XMLHttpRequest();

or best we can write this

if(window.ActiveXObject)

{

xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);

}

else if (window.XmlHttpRequest)

{

xmlHttp=new XMLHttpRequest();

}

 

xmlHttp.open(”post”, “http://localhost/WebService1/Service1.asmx/HelloWorld”, false);

The open method initializes the connection to the server and informs the xmlHttp object how to connect to the server.

post- it indicates how we want to send the data. It can be “get” as well

url- comes the url where we are connecting

false- this means we are making a synchronous call. To make asychronous call simply set it to true

xmlHttp.onreadystatechange=doUpdate;

This specifies the name of the function to be called whenever the state of the xmlHttpRequest changes

xmlHttp.send();

Send method than makes the request to server. This method would return immediately in case of asynchronous call and it would block until the synchronous response is received from the server.

if(xmlHttp.readyState==4)

It tells about the current state of the request

0- uninitialized

1- loading

2- loaded

3-interactive

4-complete

xmlHttp.responseXML.xml

It returns the current response from server in XML=

<?xml version=”1.0″?>

<string xmlns=”http://tempuri.org/”>Hello World !</string>

Than we are using some javascript functions to get the Hello World! and remove everything else.

document.forms[0].elements[‘Info’].value=exch;

Finally assigning the value to our textBox.

The function doUpdate() can be written differently so that we don’t have to make use of any string functions.

function doUpdate()

{

if(xmlHttp.readyState==4)

{

// Here the server is returning us XML in response so we can make use of responseXML

// Here the browser creates a DOM tree to represent that XML and puts a reference to that DOM tree

// in the request’s (xmlHttp) object’s responseXML

var xmlDoc=xmlHttp.responseXML;

var responseElement=xmlDoc.getElementsByTagName(”string”)[0];

var respText=responseElement.firstChild.nodeValue;

document.forms[0].elements[‘Info’].value=respText;

}

%d bloggers like this: