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...........!



No comments:

Post a Comment