Wednesday 6 June 2012

Contact Filtered Lookup based on Party List(Multi select lookup)

Create filtered lookup based on records selected in party list. We have requirement to create filtered contact lookup to selected accounts(associated child contacts) in a party list. This is quite simple like filter lookup in MS CRM 2011 but only different thing need to do is collect all GUID’s(accounts) from party list and then create FetchXML query to retrieve entire child contacts based on the all collected GUID’s(accounts) from party list.

Read party list using JavaScript and store all GUID's into Array object :-
   
var a = 0;
  var Guids = new Array();
  if (Xrm.Page.getAttribute("customers").getValue() != null) {
        var _List = Xrm.Page.getAttribute("customers").getValue();
        if (_List.length > 0) {
            for (a = 0; a < _List.length; a++) {
                Guids[a] = _List[a].id;
            }
        }
    }

Create FetchXML query to retrieve entire child contacts  :-

var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                   "<entity name='contact'>" +
                   "<attribute name='fullname' />" +
                   "<attribute name='contactid' />" +
                   "<order attribute='fullname' descending='false' />" +
                   "<link-entity name='account' from='accountid' to='parentcustomerid' alias='aa'>" +
                   "<filter type='or'>";
    for (var a = 0; a < _List.length; a++) {
        fetchXml += "<condition attribute='accountid' operator='eq' value='" + _List[a] + "'/>";
    }
    fetchXml += "</filter></link-entity></entity></fetch>";

Complete code:- 

function FilterLookup( _DisplayName, _FieldName, _Guids) {
    var viewId = "{65EC9B45-EE81-4F89-BAF6-E8603FF8E1E4}";
    var entityName = "contact";
    var viewDisplayName = "Contacts for " + _DisplayName;
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                   "<entity name='contact'>" +
                   "<attribute name='fullname' />" +
                   "<attribute name='contactid' />" +
                   "<order attribute='fullname' descending='false' />" +
                   "<link-entity name='account' from='accountid' to='parentcustomerid' alias='aa'>" +
                   "<filter type='or'>";
    for (var a = 0; a < _List.length; a++) {
        fetchXml += "<condition attribute='accountid' operator='eq' value='" + _Guids[a] + "'/>";
    }
    fetchXml += "</filter></link-entity></entity></fetch>";

    //build grid layout
    var layoutXml = "<grid name='resultset' " +

                             "object='1' " +

                             "jump='fullname' " +

                             "select='1' " +

                             "icon='1' " +

                             "preview='1'>" +

                             "<row name='result' " +

                             "id='contactid'>" +

                             "<cell name='fullname' " +

                             "width='300' />" +

                         "</row>" +

                       "</grid>";


    //add new view view
 Xrm.Page.getControl(_FieldName).addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
}


Saturday 28 April 2012

Auto Populate form fields with Associated lookup fields


let's say we have contact entity there is a lookup to associate parent customer(account). I want to auto populate some fields (Email address, Fax,Phone1 etc) in contact entity with parent customer's fields once parent customer is selected.


function GetRecord(_Filter) {
    try {
        var _Result = null;
        var _EndPoint = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";
        var _XMLHttpRequest = new XMLHttpRequest();
        _XMLHttpRequest.open("GET", _EndPoint + "/" + _Filter, false);
        _XMLHttpRequest.setRequestHeader("Accept", "application/json");
        _XMLHttpRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        var _Result = _XMLHttpRequest.send();
        if (_XMLHttpRequest.readyState == 4 && _XMLHttpRequest.status == 200) {
            _Result = this.parent.JSON.parse(_XMLHttpRequest.responseText).d;
        }
        return _Result;
    }
    catch (Err) {
        alert(Err);
        return;
    }
}


//set contacts fields based on the account selected
function SetFieldsValues() {
    var _RecordId = null;
    var _Columns = "EMailAddress1,Fax,Telephone1";
    var _Entity = "Account";
    if (Xrm.Page.getAttribute("parentcustomerid").getValue() != null) {
        _RecordId = Xrm.Page.getAttribute("parentcustomerid").getValue()[0].id;
        var _Filter = "/" + _Entity + "Set?$select=" + _Columns + "&$filter=" + _Entity + "Id eq (guid'" + _RecordId + "')";
        var _Result = GetRecord(_Filter);
        if (_Result != null && _Result.results.length == 1) {
            //set email address
            if (_Result.results[0].EMailAddress1 != null) {
                Xrm.Page.getAttribute('emailaddress1').setValue(_Result.results[0].EMailAddress1);
            }
            //set fax
            if (_Result.results[0].Fax != null) {
                Xrm.Page.getAttribute('fax').setValue(_Result.results[0].Fax);
            }

            //set Telephone
            if (_Result.results[0].Telephone1 != null) {
                Xrm.Page.getAttribute('telephone1').setValue(_Result.results[0].Telephone1);
            }
        }
    }

}


 
Call SetFieldsValues function inside OnChange event of the parent customer field.

You can change above code according to your requirement.

hope this helps someone...........!



Saturday 31 March 2012

Create connection entity record using JavaScript SOAP request in MS CRM 2011 !!!


We had a requirement, create a ribbon button on account form to create connection entity record to connect current user with the account using existing role once ribbon button pressed. here is the javascript function to create reccord :-

function CreateConnectionRecord(UserID, Accountid, RoleID) {

var request = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<s:Body>" +
"<Create xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
"<entity xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
"<a:Attributes xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
"<a:KeyValuePairOfstringanyType>" +
"<b:key>record2id</b:key>" +
"<b:value i:type='a:EntityReference'>" +
"<a:Id>" + UserID + "</a:Id>" +
"<a:LogicalName>systemuser</a:LogicalName>" +
"<a:Name i:nil='true'/>" +
"</b:value>" +
" </a:KeyValuePairOfstringanyType>" +

"<a:KeyValuePairOfstringanyType>" +
"<b:key>record1id</b:key>" +
"<b:value i:type='a:EntityReference'>" +
"<a:Id>" + Accountid + "</a:Id>" +
"<a:LogicalName>account</a:LogicalName>" +
"<a:Name i:nil='true'/>" +
"</b:value>" +
" </a:KeyValuePairOfstringanyType>" +

"<a:KeyValuePairOfstringanyType>" +
"<b:key>record2roleid</b:key>" +
"<b:value i:type='a:EntityReference'>" +
"<a:Id>" + RoleID + "</a:Id>" +
"<a:LogicalName>connectionrole</a:LogicalName>" +
"<a:Name i:nil='true'/>" +
"</b:value>" +
" </a:KeyValuePairOfstringanyType>" +

"<a:KeyValuePairOfstringanyType>" +
"<b:key>record1roleid</b:key>" +
"<b:value i:type='a:EntityReference'>" +
"<a:Id>" + RoleID + "</a:Id>" +
"<a:LogicalName>connectionrole</a:LogicalName>" +
"<a:Name i:nil='true'/>" +
"</b:value>" +
" </a:KeyValuePairOfstringanyType>" +

"</a:Attributes>" +
"<a:EntityState i:nil='true'/>" +
"<a:FormattedValues xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'/>" +
"<a:Id>00000000-0000-0000-0000-000000000000</a:Id>" +
"<a:LogicalName>connection</a:LogicalName>" +
"<a:RelatedEntities xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'/>" +
"</entity>" +
"</Create>" +
"</s:Body>" +
"</s:Envelope>";

ExecuteRequest(request, "Create");

}

function ExecuteRequest(_XML, Message) {
    try {
        var _ResultXML = null;
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("POST", Xrm.Page.context.getServerUrl() + "/XRMServices/2011/Organization.svc/web", false);
        xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
        xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/" + Message);
        xmlhttp.send(_XML);
        _ResultXML = xmlhttp.responseXML;
        var errorCount = _ResultXML.selectNodes('//error').length;
        if (errorCount != 0) {
            var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
            alert(msg);
            _ResultXML = null;
            return _ResultXML;
        }
        else {
            return _ResultXML;
        }
    }
    catch (Err) {
        alert(Err);
        return;
    }
}


Pass current userid, accountid and roleid to CreateConnectionRecord function.

Hope this helps………!!!



Retrieve multiple records using JavaScript SOAP request in MS CRM 2011 !!!


Below example to retrieve accountid based on the account name from account entity:-

function ExecuteRequest(_XML, Message) {
    try {
        var _ResultXML = null;
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("POST", Xrm.Page.context.getServerUrl() + "/XRMServices/2011/Organization.svc/web", false);
        xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
        xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/" + Message);
        xmlhttp.send(_XML);
        _ResultXML = xmlhttp.responseXML;
        var errorCount = _ResultXML.selectNodes('//error').length;
        if (errorCount != 0) {
            var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
            alert(msg);
            _ResultXML = null;
            return _ResultXML;
        }
        else {
            return _ResultXML;
        }
    }
    catch (Err) {
        alert(Err);
        return;
    }

function GetMultipleAccounts(AccountName) {

    var request = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
                 "<s:Body>" +
                 "<RetrieveMultiple xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services'     xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
                 "<query i:type='a:QueryExpression' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
                 "<a:ColumnSet>" +
                 "<a:AllColumns>false</a:AllColumns>" +
                 "<a:Columns xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
                 "<b:string>accountid</b:string>" +
                 "</a:Columns>" +
                 "</a:ColumnSet>" +
                 "<a:Criteria>" +
                 "<a:Conditions>" +
                 "<a:ConditionExpression>" +
                 "<a:AttributeName>name</a:AttributeName>" +
                 "<a:Operator>Equal</a:Operator>" +
                 "<a:Values xmlns:b='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>" +
                 "<b:anyType i:type='c:string' xmlns:c='http://www.w3.org/2001/XMLSchema'>" + AccountName + "</b:anyType>" +
                 "</a:Values>" +
                 "</a:ConditionExpression>" +
                 "</a:Conditions>" +
                 "<a:FilterOperator>And</a:FilterOperator>" +
                 "<a:Filters />" +
                 "</a:Criteria>" +
                 "<a:Distinct>false</a:Distinct>" +
                 "<a:EntityName>account</a:EntityName>" +
                 "<a:LinkEntities />" +
                 "<a:Orders />" +
                 "<a:PageInfo>" +
                 "<a:Count>0</a:Count>" +
                 "<a:PageNumber>0</a:PageNumber>" +
                 "<a:PagingCookie i:nil='true' />" +
                 "<a:ReturnTotalRecordCount>true</a:ReturnTotalRecordCount>" +
                 "</a:PageInfo>" +
                 "<a:NoLock>false</a:NoLock>" +
                 "</query>" +
                 "</RetrieveMultiple>" +
                 "</s:Body>" +
                 "</s:Envelope>";

    var _ResultXML = ExecuteRequest(request, "RetrieveMultiple");
    var count = _ResultXML.selectSingleNode("//a:TotalRecordCount").text;
    if (count >= 1) {
        var ID = _ResultXML.selectSingleNode("//a:Id").text
        return ID;
    }
    else
        return null;
}

Call GetMultipleAccounts function like as below:-

var _Id = GetMultipleAccounts(“Microsoft”);

Cheers !!!