CRM 2011 - setting a default value with JScript

二次信任 提交于 2019-12-02 09:55:22

It's very bad practice to hard code your GUIDs and you discovered the problems of it. As you stated above, we cannot have the same GUIDs but we have the same name. So, we have to query the name of the country using JScript and jQuery to retrieve the GUID.

In order to retireve information from client-side (or Entity Form):

  1. We will use/consume REST Endpoint (testing in browser).
  2. Upload jQuery lib.
  3. Upload Json2 lib.
  4. Use the AJAX function from the jQuery library.
  5. Define your entity, columns and criteria.

Lets, look for querying REST Endpoint.

 http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'

Take this URL, subsitute your actual values and paste it into your browser, you'll find that the response is returned in XML format. If there is any error, please ensure that the Entity name and its attribute are case senisitve.

After seeing your your results, we are going to call this URL using an AJAX call.

$.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                url: 'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet?$select=new_Name,new_CountryId&$filter=new_Name eq 'Canada'',
                beforeSend: function (XMLHttpRequest) {
                    //Specifying this header ensures that the results will be returned as JSON.             
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                success: function (data) {
                    if (data.d && data.d.results) {
                        //var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
                        var _canadaId = data.d.results[0].ContactId;

                        // now we have the GUID of Canada, now I can continue my process

                    }

                },
                error: function (XmlHttpRequest) {

                    alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
                }

            });

But before you copy the code to your form, you have to download the jQuery lib from here Then upload it as a Web resource, add this web resource to the Form load libs.

Here is the complete code to be put in the form load event handler:

var context = GetGlobalContext();

// retireve the invoice record id (Opened Form)
var invoiceId = context.getQueryStringParameters().id;
var customerId;

//Retrieve the server url, which differs on-premise from on-line and 
//shouldn't be hard-coded.
// this will return something like http://yourHostName/yourOrg
var serverUrl = context.getServerUrl();


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

var odataUri = serverUrl + ODATA_ENDPOINT;

function SetDefaultCountryCode(countryFieldId, odataUri) {

    odataUri = odataUri + '/ContactSet?$select=ContactId,FullName&$filter=FullName eq \'Ahmed Shawki\'';
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataUri,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data) {
            if (data.d && data.d.results) {
                //var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}"; no longer be used
                var _canadaId = data.d.results[0].ContactId;

                var countryControl = Xrm.Page.getAttribute(countryFieldId);

                // only attempt the code if the control exists on the form
                if (countryControl != null) {
                    var currentCountry = countryControl.getValue();

                    // if country is not specified, then set it to the default one (Canada) 
                    if (currentCountry == null) {
                        var defaultCountry = new Object();
                        defaultCountry.entityType = "cga_country";
                        defaultCountry.id = _canadaId;
                        defaultCountry.name = "Canada";
                        var countryLookupValue = new Array();
                        countryLookupValue[0] = defaultCountry;

                        countryControl.setValue(countryLookupValue);
                    }
                }
            }

        },
        error: function (XmlHttpRequest) {

            alert("Error : " + XmlHttpRequest.status + ": " + XmlHttpRequest.statusText + ": " + JSON.parse(XmlHttpRequest.responseText).error.message.value);
        }

    });

}

One more thing, don't forget to check "Pass execution context as first parameter" box on the form properties.

EDIT: Beside adding the jQuery library into the form load event handler, add the Json2 lib as a web resource.

For more information about the REST Endpoint.

It is indeed possible to export and import records along with their guids, just not natively. You'd have to build an app that would export the data for you, then create identical records through the CRM API in the target environment. You just have to clear out fields that aren't valid for create (createdon, statecode, etc.) and just specify the same Guid. CRM will then create the record with that Guid.

The old 4.0 Configuration Data Tool does this. I can't recall if it works against a 2011 org, but it could be a starting point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!