CRM 2011-使用JScript设置默认值 [英] CRM 2011 - setting a default value with JScript

查看:71
本文介绍了CRM 2011-使用JScript设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在内部安装了CRM 2011。自定义联系人实体以使用对自定义实体国家/地区的查找,而不仅仅是文本字段。在创建新联系人时,我们希望将国家/地区字段默认设置为加拿大。我有执行此操作的以下函数:

 函数SetDefaultCountryCode(countryFieldId){

var _canadaId = {FC167B4D-1C3B-E111-8904-F2EA3FE25706};

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

//仅当控件以
形式存在时才尝试代码if(countryControl!= null){
var currentCountry = countryControl.getValue();

//如果未指定国家/地区,则将其设置为默认值(加拿大)
if(currentCountry == null){
var defaultCountry = new Object();
defaultCountry.entityType = cga_country;
defaultCountry.id = _canadaId;
defaultCountry.name =加拿大;
var countryLookupValue = new Array();
countryLookupValue [0] = defaultCountry;

countryControl.setValue(countryLookupValue);
}
}
}

在OnLoad表单上我调用像这样的函数:

  //如果未设置
,则将Country字段设置为Canada SetDefaultCountryCode('cga_address1country');

我们有两台服务器-DEV和TEST。此JScript在DEV中工作正常。当我在TEST中运行它时,它不起作用,因为在TEST中的加拿大具有不同的ID(GUID)-当我手动创建它时。我希望可以从DEV导出Country实体值并将其导入TEST中,以保留其GUID。不幸的是,这没有用。我将数据导出到Excel文件,并且具有国家/地区的GUID。在导入之前,我还要删除TEST中所有现有的国家/地区记录。当我尝试导入时,导入成功,但是不创建任何记录。如果我在excel文件中添加新行而未指定Guid,它将导入它。在我看来,导入功能并不是要保留记录的GUID。但这也意味着我的脚本无法工作,因为它取决于GUID。



我在这里有两个问题:


  1. 是否可以导出/导入保留GUID的实体数据?


  2. 如果我不能使用相同的GUID在DEV和TEST中如何使JScript正常工作?


在此先感谢您的帮助/反馈

解决方案

对GUID进行硬编码是很不好的做法,您发现了它的问题。
如上所述,我们不能具有相同的GUID,但是名称相同。因此,我们必须使用JScript和jQuery来查询国家名称以检索GUID。



为了从客户端(或实体表单)检索信息:


  1. 我们将使用/使用REST端点(在浏览器中测试)。

  2. 上载jQuery lib。

  3. 上传Json2库。

  4. 使用jQuery库中的AJAX函数。

  5. 定义实体,列和条件。

让我们查找查询REST端点。

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

使用此URL,替换您的实际值并将其粘贴到浏览器中,您将发现响应以XML格式返回。如果有任何错误,请确保实体名称及其属性为 case senisitve



看到您的结果后,我们将来使用AJAX调用来调用此URL。

  $。ajax({
type: GET,
contentType:应用程序/ json; charset = utf-8,
数据类型: json,
网址:'http://yourHostName/yourOrg/XRMServices/2011/OrganizationData.svc/new_CountrytSet $ select = new_Name,new_CountryId& $ filter = new_Name eq'Canada',
beforeSend:function(XMLHttpRequest){
//指定此标头可确保结果将作为JSON返回。 $ b XMLHttpRequest.setRequestHeader( Accept, application / json);
},
成功:函数(数据){
if(data.d&& data.d .results){
// var _canadaId = {FC167B4D-1C3B-E111-8904-F2EA3FE25706};不再使用
var _canadaId = data.d.results [0] .ContactId;

//现在我们有了加拿大的GUID,现在我可以继续我的过程

}

},
错误:函数(XmlHttpRequest){

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

});

但是在将代码复制到表单之前,必须从此处
然后将其作为Web资源上载,将此Web资源添加到Form load libs中。



这是要放入表单加载事件处理程序中的完整代码:

  var context = GetGlobalContext(); 

//提取发票记录ID(打开的表单)
var invoiceId = context.getQueryStringParameters()。id;
var customerId;

//检索服务器的url,该URL在本地与在线不同,并且
//不应进行硬编码。
//这将返回类似http:// yourHostName / yourOrg
var serverUrl = context.getServerUrl();


// XRM OData端点
var ODATA_ENDPOINT = /XRMServices/2011/OrganizationData.svc;

var odataUri = serverUrl + ODATA_ENDPOINT;

函数SetDefaultCountryCode(countryFieldId,odataUri){

odataUri = odataUri +'/ ContactSet?$ select = ContactId,FullName& $ filter = FullName eq A'Ahmed Shawki\ \'';
$ .ajax({
type: GET,
contentType: application / json; charset = utf-8,
数据类型: json,
url:odataUri,
beforeSend:函数(XMLHttpRequest){
//指定此标头可确保结果将作为JSON返回。
XMLHttpRequest.setRequestHeader( Accept, application / json);
},
成功:函数(数据){
if(data.d&& data.d.results){
// var _canadaId = {FC167B4D-1C3B-E111-8904-F2EA3FE25706};不再使用
var _canadaId = data.d.results [0] .ContactId;

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

//仅当控件以
形式存在时尝试尝试代码if(countryControl!= null){
var currentCountry = countryControl.getValue( );

//如果未指定国家/地区,则将其设置为默认值(加拿大)
if(currentCountry == null){
var defaultCountry = new Object();
defaultCountry.entityType = cga_country;
defaultCountry.id = _canadaId;
defaultCountry.name =加拿大;
var countryLookupValue = new Array();
countryLookupValue [0] = defaultCountry;

countryControl.setValue(countryLookupValue);
}
}
}

},
错误:函数(XmlHttpRequest){

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

});

}

还有一件事情,别忘了检查 <

EDIT :在表单属性上的框上添加。表单加载事件处理程序,将 Json2 lib添加为网络资源。



有关 REST端点的更多信息。 / p>

We have CRM 2011 on premise. The Contact entity was customized to use a lookup to a custom entity Country instead of just a text field. When creating a new Contact we would like the country field to be set to Canada by default. I have the following function that does that:

            function SetDefaultCountryCode(countryFieldId) {

                var _canadaId = "{FC167B4D-1C3B-E111-8904-F2EA3FE25706}";

                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);
                    }
                }
            }

On the form OnLoad I invoke the function like that:

    // set Country fields to Canada if not set
    SetDefaultCountryCode('cga_address1country');

We have two servers - DEV and TEST. This JScript works fine in DEV. When I run it in TEST it does not work because the Canada in TEST has different id (GUID) - when I create it manually. I was hoping I could export the Country entity values from DEV and import them in TEST preserving their GUIDs. Unfortunately this did not work. I export the data to Excel file and it has the GUIDs of the countries. I also delete any existing Country records in TEST before importing. When I try to import it the import succeeds but does not create any records. If I add a new row in the excel file without specifing a Guid it will import it. It seems to me the import functionality was not meant to preserve the GUIDs of the records. But this also means my script will not work because it depends on the GUIDs.

I have two questions here:

  1. Is it possible to export / import entity data preserving the GUIDs ?

  2. If I cannot have the same GUIDs in DEV and TEST how I can make the JScript to work properly?

Thank you in advance for any help / feedback.

解决方案

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.

这篇关于CRM 2011-使用JScript设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆