CRM2011 js 通过服务操作实体

/*-说明:通用JS函数库
创建者:
创建时间:2012-05-08
-*/
// tab键从左到右。windows onload时调用
function TabOrderLefttoRight() {
    for (var i = 0; i < crmForm.all.length; i++) {
        var element = crmForm.all[i];
        if (element.tabIndex && element.tabIndex != "0") {
            if (element.className == 'ms-crm-Hidden-NoBehavior')
                continue;
            if (element.tagName == 'A') {
                if (element.className != 'ms-crm-InlineTabHeaderText')
                    continue;
            }
            element.tabIndex = 10000 + (i * 10);
        }
    }
}
/*根据实体主键值(entityGuid)查询指定实体(entityName)的一条记录
如:var resultObject=retrieveSingleEntity(ODataPath,"Account",accountid);
var retrieved = resultObject.response;
var statusText = resultObject.statusText;
*/
retrieveSingleEntity = function (ODataPath, entitySchemaName, entityGuid) {
    var retrieveReq = new XMLHttpRequest();
    //实体名称区分大小写,查询地址http://CRM应用服务器IP/CRM组织名/XRMServices/2011/OrganizationData.svc
    retrieveReq.open("GET", ODataPath + "/XRMServices/2011/OrganizationData.svc/" + entitySchemaName + "Set(guid'" + entityGuid + "')", false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.send();
    var resultObject = new Object();
    resultObject.statusText = null;
    resultObject.response = null;
    if (retrieveReq.statusText == "OK") { //OK为查询成功,否则查询异常
        resultObject.statusText = "OK";
        resultObject.response = JSON.parse(retrieveReq.responseText).d;
    } else {
        resultObject.response = retrieveReq.responseText;
    }

    return resultObject;
}
/*根据ODATA参数查询指定实体(entityName)的多条记录
如:var select=name,accountnumber; var filter=statecode/Value eq 0; var orderby=accountid; var expand=""; var top=2; var skip=2;
var resultObject=retrieveMultipleEntity(ODataPath,"Account", select, filter, orderby, expand, top, skip);
var retrieved = resultObject.response;
var statusText = resultObject.statusText;
*/
function retrieveMultipleEntity(ODataPath, entitySchemaName, select, filter, orderby, expand, top, skip) {
    var retrieveParams = "";
    if (typeof (select) != "undefined" && select != null && select != "") {
        retrieveParams = retrieveParams + "&$select=" + select;
    }
    if (typeof (filter) != "undefined" && filter != null && filter != "") {
        retrieveParams = retrieveParams + "&$filter=" + filter;
    }
    if (typeof (orderby) != "undefined" && orderby != null && orderby != "") {
        retrieveParams = retrieveParams + "&$orderby=" + orderby;
    }
    if (typeof (expand) != "undefined" && expand != null && expand != "") {
        retrieveParams = retrieveParams + "&$expand=" + expand;
    }
    if (typeof (top) != "undefined" && top != null && top != "") {
        retrieveParams = retrieveParams + "&$top=" + top;
    }
    if (typeof (skip) != "undefined" && skip != null && skip != "") {
        retrieveParams = retrieveParams + "&$skip=" + skip;
    }
    if (retrieveParams != "" && retrieveParams != null) {
        retrieveParams = retrieveParams.substring(1, retrieveParams.length);
    }
    var retrieveReq = new XMLHttpRequest();
    retrieveReq.open("GET", ODataPath + "/XRMServices/2011/OrganizationData.svc/" + entitySchemaName + "Set?" + retrieveParams, false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.send();

    var resultObject = new Object();
    resultObject.statusText = null;
    resultObject.response = null;
    if (retrieveReq.statusText == "OK") { //OK为查询成功,否则查询异常
        resultObject.statusText = "OK";
        resultObject.response = JSON.parse(retrieveReq.responseText).d;
    } else {
        resultObject.response = retrieveReq.responseText;
    }

    return resultObject;
}
/*创建一条实体实例记录
var AccountObject=new Object();
AccountObject.name="CRM客户";
var resultObject=createRecord(serverUrl,"Account",AccountObject);
var retrieved = resultObject.response;
var statusText = resultObject.statusText;
*/
function createRecord(serverUrl, entitySchemaName, entityObject) {
    var createReq = new XMLHttpRequest();
    createReq.open("POST", serverUrl + "/XRMServices/2011/OrganizationData.svc/" + entitySchemaName + "Set", false);
    createReq.setRequestHeader("Accept", "application/json");
    createReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    createReq.send(JSON.stringify(entityObject));

    var resultObject = new Object();
    resultObject.statusText = null;
    resultObject.response = null;

    if (createReq.statusText == "Created") { //Created为创建成功,否则创建异常
        resultObject.statusText = "OK";
        resultObject.response = JSON.parse(createReq.responseText).d;
    } else {
        resultObject.response = createReq.responseText;
    }

    return resultObject;
}
/*更新一条实体实例记录
var entityGuid="00000000-0000-0000-0000-000000000000";
var AccountObject=new Object();
AccountObject.name="CRM客户";
var resultObject=updateRecord(serverUrl,"Account",entityGuid,AccountObject);
var retrieved = resultObject.response;
var statusText = resultObject.statusText;
*/
function updateRecord(serverUrl, entitySchemaName, entityGuid, entityObject) {
    var resultObject = new Object();
    resultObject.statusText = null;
    resultObject.response = null;

    if (entityGuid != null && entityGuid != "") {
        var updateReq = new XMLHttpRequest();
        updateReq.open("POST", serverUrl + "/XRMServices/2011/OrganizationData.svc/" + entitySchemaName + "Set(guid'" + entityGuid + "')", false);
        updateReq.setRequestHeader("Accept", "application/json");
        updateReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        updateReq.setRequestHeader("X-HTTP-Method", "MERGE");
        updateReq.send(JSON.stringify(entityObject));

        resultObject.statusText = updateReq.statusText;
        if (updateReq.statusText == "Unknown") { //Unknown为更新成功,否则更新异常
            resultObject.statusText = "OK";
        } else {
            resultObject.response = updateReq.responseText;
        }
    } else {
        alert("updateRecord requires the entityGuid parameter!");
        resultObject.statusText = "Failed";
    }
    return resultObject;
}
/*删除一条实体实例记录
var resultObject=deleteRecord(serverUrl,"Account","00000000-0000-0000-0000-000000000000");
var retrieved = resultObject.response;
var statusText = resultObject.statusText;
*/
function deleteRecord(serverUrl, entitySchemaName, entityGuid) {
    var deleteReq = new XMLHttpRequest();
    deleteReq.open("POST", serverUrl + "/XRMServices/2011/OrganizationData.svc/" + entitySchemaName + "Set(guid'" + entityGuid + "')", false);
    deleteReq.setRequestHeader("Accept", "application/json");
    deleteReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    deleteReq.setRequestHeader("X-HTTP-Method", "DELETE");
    deleteReq.send();

    var resultObject = new Object();
    resultObject.statusText = null;
    resultObject.response = null;

    if (deleteReq.statusText == "Unknown") {
        resultObject.statusText = "OK"; //Unknown为删除成功,否则删除异常
    } else {
        resultObject.response = deleteReq.responseText;
    }

    return resultObject;
}
/*查询自定义的多语言文本(languageCode:语言代码 purposeType:用途类型[10:脚本 20:插件 30:门户系统 40:自定义页面 50:自定义Web Service] 应用模块:applyModule)
如:var select=name,accountnumber; var filter=statecode/Value eq 0; var orderby=accountid; var expand=""; var top=2; var skip=2;
var listLangText=getMultiLangTextList(ODataPath,2052, 10 ,"account");
*/
function getMultiLangTextList(ODataPath, languageCode, purposeType, applyModule) {
    var retrieveParams = "$select=new_code,new_text"
+ "&$filter=new_language_code eq " + languageCode
+ " and new_purposetype/Value eq " + purposeType
+ " and new_applymodule eq '" + applyModule + "'";

    var retrieveReq = new XMLHttpRequest();
    retrieveReq.open("GET", ODataPath + "/XRMServices/2011/OrganizationData.svc/new_multi_language_mappingSet?" + retrieveParams, false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.send();

    var resultObject = new Object();
    resultObject.statusText = retrieveReq.statusText;
    resultObject.response = null;
    if (resultObject.statusText == "OK") { //OK为查询成功,否则查询异常
        resultObject.response = JSON.parse(retrieveReq.responseText).d;
    } else {
        resultObject.response = retrieveReq.responseText;
    }

    return resultObject;
}
/*判断当前用户是否拥有指定的安全角色
如:var blnCheckResult=checkUserHasRole(serverUrl, "系统管理员");
*/
function checkUserHasRole(serverUrl, roleName) {
    var Path = serverUrl + "/XRMServices/2011/OrganizationData.svc/RoleSet?$filter=";
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
        Path += "RoleId eq (guid'" + currentUserRoles[i] + "') or ";
    }
    Path = Path.substring(0, Path.length - 3);
    var retrieveReq = new XMLHttpRequest();
    retrieveReq.open("GET", Path, false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.send();
    var retrieved = JSON.parse(retrieveReq.responseText).d;
    if (retrieved != null && retrieved.results.length > 0) {
        for (var j = 0; j < retrieved.results.length; j++) {
            if (roleName == retrieved.results[j].Name) {
                return true;
            }
        }
    }
    return false
}
/*判断指定用户是否拥有指定的安全角色
如:var blnCheckResult=checkUserHasRole(serverUrl, "系统管理员","D8AB5312-0744-E211-BA39-00155D002F0D");
*/
function checkUserHasRoleById(serverUrl, roleName, userId) {
    var filter_userid = "SystemUserId eq guid'" + userId + "'";
    var resultObject = retrieveMultipleEntity(serverUrl, "SystemUserRoles", null, filter_userid, null, null, null, null);
    var retrieved = resultObject.response;
    var statusText = resultObject.statusText;
    if (statusText == "OK" && retrieved != null && retrieved.results != undefined && retrieved.results.length > 0) {
        var filter_roleIds = "";
        for (var i = 0; i < retrieved.results.length; i++) {
            filter_roleIds += "RoleId eq (guid'" + retrieved.results[i].RoleId + "') or ";
        }
        filter_roleIds = filter_roleIds.substring(0, filter_roleIds.length - 3);
        if (filter_roleIds != "") {
            var retrieveRole = retrieveMultipleEntity(serverUrl, "Role", "Name", filter_roleIds, null, null, null, null);
            if (retrieveRole.statusText == "OK" && retrieveRole.response != null && retrieveRole.response.results != null
&& retrieveRole.response.results != undefined && retrieveRole.response.results.length > 0) {
                for (var j = 0; j < retrieveRole.response.results.length; j++) {
                    if (roleName == retrieveRole.response.results[j].Name) {
                        return true;
                    }
                }
            }
        }
    }

    return false
}
/*获取用于OData查询的日期时间类型字段的查询条件的值,返回UTC日期时间
参数说明:date:日期时间类型的变量,如var nowDate=new Date(),nowDate可作为参数值
*/
function getODataUTCDateFilter(date) {
    var monthString;
    var rawMonth = date.getUTCMonth().toString();
    if (rawMonth.length == 1) {
        monthString = "0" + rawMonth;
    } else {
        monthString = rawMonth;
    }

    var dateString;
    var rawDate = date.getUTCDate().toString();
    if (rawDate.length == 1) {
        dateString = "0" + rawDate;
    } else {
        dateString = rawDate;
    }

    var DateFilter = "datetime\'";
    DateFilter += date.getUTCFullYear() + "-";
    DateFilter += monthString + "-";
    DateFilter += dateString;
    DateFilter += "T" + date.getUTCHours() + ":";
    DateFilter += date.getUTCMinutes() + ":";
    DateFilter += date.getUTCSeconds() + ":";
    DateFilter += date.getUTCMilliseconds();
    DateFilter += "Z\'";
    return DateFilter;
}
/*获取用于OData查询的日期时间类型字段的查询条件的值,返回Local日期时间
参数说明:1.date:日期时间类型的变量,如var nowDate=new Date(),nowDate可作为参数值
2.timePoint:具体的时间点,如10:00:00(10点整)、10:30:00(10点30分)
*/
function getODataDateFilter(date, timePoint) {
    var monthString;
    var rawMonth = (date.getMonth() + 1).toString();
    if (rawMonth.length == 1) {
        monthString = "0" + rawMonth;
    } else {
        monthString = rawMonth;
    }

    var dateString;
    var rawDate = date.getDate().toString();
    if (rawDate.length == 1) {
        dateString = "0" + rawDate;
    } else {
        dateString = rawDate;
    }

    var hoursString;
    var rawHours = date.getHours() - 8; //CRM数据库中保存的时间为操作系统时间减8小时
    hoursString = "0" + rawHours.toString();
    hoursString = hoursString.substr(hoursString.length - 2, 2);

    var minutesString;
    var rawMinutes = date.getMinutes();
    minutesString = "0" + rawMinutes.toString();
    minutesString = minutesString.substr(minutesString.length - 2, 2);

    var secondsString;
    var rawSeconds = date.getSeconds();
    secondsString = "0" + rawSeconds.toString();
    secondsString = secondsString.substr(secondsString.length - 2, 2);

    var filterDateString = date.getFullYear() + "-" + monthString + "-" + dateString;
    var filterTimeString = "";
    if (timePoint != null && timePoint != "" && typeof (timePoint) != "undefined") {
        var timeHour = parseInt(timePoint.substr(0, 2)) - 8; //CRM数据库中保存的时间为操作系统时间减8小时
        var timeHourString = "0" + timeHour.toString();
        timeHourString = timeHourString.substr(timeHourString.length - 2, 2);
        filterTimeString = timeHourString + timePoint.substr(2, timePoint.length);
    }
    else {
        filterTimeString = hoursString + ":" + minutesString + ":" + secondsString;
    }

    var DateFilter = "datetime\'";
    DateFilter += filterDateString;
    DateFilter += "T";
    DateFilter += filterTimeString;
    DateFilter += "Z\'";
    return DateFilter;
}
/*日期增加函数
如:增加一天dateAdd("d",1,new Date())、减少一天dateAdd("d",-1,new Date())
*/
function dateAdd(strInterval, addNum, baseDate) {
    var dtTmp = new Date(baseDate);
    if (isNaN(dtTmp)) dtTmp = new Date();
    switch (strInterval) {
        case "s": return new Date(Date.parse(dtTmp) + (1000 * addNum));
        case "n": return new Date(Date.parse(dtTmp) + (60000 * addNum));
        case "h": return new Date(Date.parse(dtTmp) + (3600000 * addNum));
        case "d": return new Date(Date.parse(dtTmp) + (86400000 * addNum));
        case "w": return new Date(Date.parse(dtTmp) + ((86400000 * 7) * addNum));
        case "m": return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + addNum, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case "y": return new Date((dtTmp.getFullYear() + addNum), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
}

/*更改功能区Ribbon按钮的状态(启用或禁用):如 SetRibbonState(3, "否决", true);
参数说明:index:按钮在功能的位置(从0开始) text:按钮上的文字说明 disabled:是否禁用(禁用:true 启用:false)
*/
function setRibbonState(index, text, disabled) {
    Concurrent.Thread.create(function (i, t, d) {
        while ($('.ms-cui-tabContainer a', parent.document).eq(i).find("span").eq(2)[0].innerText != t) {

        }
        if ($('.ms-cui-tabContainer a', parent.document).eq(i).find("span").eq(2)[0].innerText == t) {
            $('.ms-cui-tabContainer a', parent.document).eq(i).children().attr("disabled", d);
            $('.ms-cui-tabContainer a', parent.document).eq(i).attr("disabled", d);
        }
    }, index, text, disabled);
}
/*设置功能区Ribbon按钮的样式:SetRibbonStyle(3, "否决", "display: none;");
参数说明:index:按钮在功能的位置(从0开始) text:按钮上的文字说明 style:css样式属性及属性的值
*/
function setRibbonStyle(index, text, style) {
    Concurrent.Thread.create(function (i, t, d) {
        while ($('.ms-cui-tabContainer a', parent.document).eq(i).find("span").eq(2)[0].innerText != t) {

        }
        if ($('.ms-cui-tabContainer a', parent.document).eq(i).find("span").eq(2)[0].innerText == t) {
            $('.ms-cui-tabContainer a', parent.document).eq(i).children().attr("style", d);
            $('.ms-cui-tabContainer a', parent.document).eq(i).attr("style", d);
        }
    }, index, text, style);
}
//信息提醒:如NotificationAlert("Warning", "警告:系统中该样品库存数量已经不足!");
function notificationAlert(AlertType, AlertString, PageType, DisplayTime) {
    if (typeof (PageType) == undefined || PageType == null) {
        PageType = "Form";
    }
    var notificationsArea;
    if (PageType == "HomeGrid") {
        notificationsArea = document.getElementById('crmAppMessageBar'); //主界面(HomeGrid)为crmAppMessageBar
    } else {
        notificationsArea = document.getElementById('crmNotifications'); //表单界面(Form)为crmNotifications
    }
    if (notificationsArea == null) {
        alert('未能找到提醒信息显示控件,请联系系统管理员咨询!');
        return;
    }
    hideNotification(PageType);
    if (AlertType == "Critical") {
        notificationsArea.AddNotification('mep1', 1, 'source', AlertString);
        AlertType = "None";
    }
    else if (AlertType == "Warning") {
        notificationsArea.AddNotification('mep2', 2, 'source', AlertString);
        AlertType = "None";
    }
    else if (AlertType == "Info") {
        notificationsArea.AddNotification('mep3', 3, 'source', AlertString);
        AlertType = "None";
    }
    else {
        notificationsArea.SetNotifications(null, null);
        AlertType = "None";
    }

    if (typeof (DisplayTime) == undefined || DisplayTime == null || DisplayTime == "" || DisplayTime < 5000) DisplayTime = 5000;
    setTimeout("hideNotification('" + PageType + "');", DisplayTime);
}
//隐藏CRM提示区域
function hideNotification(PageType) {
    var notificationsArea;
    if (PageType == "HomeGrid") {
        notificationsArea = document.getElementById('crmAppMessageBar'); //主界面(HomeGrid)为crmAppMessageBar
    } else {
        notificationsArea = document.getElementById('crmNotifications'); //表单界面(Form)为crmNotifications
    }
    //notificationsArea.style.display = 'none';
    notificationsArea.SetNotifications(null, null);
}
/*-获取服务器时间-*/
function getServerDate() {
    var xmlHTTPRequest;
    if (window.ActiveXObject) {
        xmlHTTPRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHTTPRequest = new XMLHttpRequest();
    }
    else {
        xmlHTTPRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }
    xmlHTTPRequest.open('HEAD', '/?_=' + (-new Date), false);
    xmlHTTPRequest.send(null);

    var serverDate = new Date(xmlHTTPRequest.getResponseHeader('Date'));

    return serverDate;
}

/*修改Lookup选择窗口的URL参数的值 begin*/
//禁用选择视图功能:document.getElementById("LookupFieldName").setAttribute("disableViewPicker", "1");
function modifiedLookupParameter(fieldName, parameterName, parameterValue) {
    document.getElementById(fieldName).setAttribute(parameterName, parameterValue);
}
/*获取指定文本框控件下的指定的html元素
如:var new_accountid_d_div = getLookupQuickFindElement("new_accountid", "div");
*/
function getLookupQuickFindElement(crmFieldName, tagName) {
    //var contentIframe = top.document.getElementById("contentIFrame");
    var oLookupTextControl = document.getElementById(crmFieldName + "_d");
    var lookupitem = oLookupTextControl.getElementsByTagName(tagName);
    if (lookupitem.length > 0) {
        return lookupitem[0];
    }
}
/*自动展开表单中,对指定lookup字段模糊快速查找后的下拉列表
如:showLookupQuickFindList("new_accountid");
*/
function showLookupQuickFindList(crmFieldName) {
    var lookupitem_span = getLookupQuickFindElement(crmFieldName, "span");
    if (lookupitem_span != undefined && lookupitem_span != null) {
        var lookupitem_img = lookupitem_span.getElementsByTagName("img");
        if (lookupitem_img.length > 0 && lookupitem_img[0].getAttribute("imageSrc") == "/_imgs/error/notif_icn_warn16.png") {
            lookupitem_span.click();
        }
    }

}
/*获取查找类型字段值的对象(适用于表单)
如:var entityReferent=getEntityReferenceObject(accountid,"account","CRM客户");
*/
function getEntityReferenceObject(id, entityType, name) {
    var lookupReference = [];
    lookupReference[0] = {};
    lookupReference[0].id = id;
    lookupReference[0].entityType = entityType;
    lookupReference[0].name = name;

    return lookupReference;
}
//禁用表单字段
function disabledControls() {
    var controls = Xrm.Page.ui.controls.get();
    for (var i in controls) {
        var control = controls[i];
        if (control.getDisabled() == false) {
            control.setDisabled(true);
        }
    }
}
//禁用子网格
function disableSubGrid(subGridName) {
    try {
        var subGrid = document.getElementById(subGridName + "_span");
        if (subGrid) {
            subGrid.disabled = true;
        }
    } catch (e) { }
}
/*将当前鼠标焦点移除到CrmForm(表单主体)之外
如:setFormFieldsBlur(); 此方法通常用于Ribbon控件的onclick事件中
*/
function setFormFieldsBlur() {
    var fixedControl = top.document.getElementById("helponthispage"); //关于此页面的帮助
    if (fixedControl == undefined || fixedControl == null) {
        fixedControl = top.document.getElementById("minimizeribbon"); //隐藏功能区
    }
    fixedControl.focus();
}
/*设置指定节(section)下的所有字段是否只读(sectionControl:节控件对象 blnIsDisabled:设置是否只读[true:只读 false:可编辑])
如:var sectionControl=Xrm.Page.ui.tabs.get("tab_general").sections.get("section_general");
setSectionFieldsStatus(sectionControl,true);
*/
function setSectionFieldsStatus(sectionControl, blnIsDisabled) {
    if (!sectionControl.getVisible() || sectionControl.controls.get() == null) return;
    for (var i = 0; i < sectionControl.controls.get().length; i++) {
        var fieldControl = sectionControl.controls.get()[i];
        if (fieldControl.getVisible()) {
            fieldControl.setDisabled(blnIsDisabled);
        }
    }
}
/*设置指定节(section)下的所有字段置空(sectionControl:节控件对象)
如:var sectionControl=Xrm.Page.ui.tabs.get("tab_general").sections.get("section_general");
resetSectionFieldsValue(sectionControl);
*/
function resetSectionFieldsValue(sectionControl) {
    if (!sectionControl.getVisible() || sectionControl.controls.get() == null) return;
    for (var i = 0; i < sectionControl.controls.get().length; i++) {
        var fieldControl = sectionControl.controls.get()[i];
        if (fieldControl.getVisible()) {
            if (fieldControl.getControlType().toLowerCase() != "subgrid") {
                var field = fieldControl.getAttribute();
                field.setValue(null);
            }
        }
    }
}
/*设置指定节(section)下的所有字段是否只读,且置空字段的值(sectionControl:节控件对象 blnIsDisabled:设置是否只读[true:只读 false:可编辑])
如:var sectionControl=Xrm.Page.ui.tabs.get("tab_general").sections.get("section_general");
setSectionFieldsStatusAndReset(sectionControl,true);
*/
function setSectionFieldsStatusAndReset(sectionControl, blnIsDisabled) {
    if (!sectionControl.getVisible() || sectionControl.controls.get() == null) return;
    for (var i = 0; i < sectionControl.controls.get().length; i++) {
        var fieldControl = sectionControl.controls.get()[i];
        if (fieldControl.getVisible()) {
            fieldControl.setDisabled(blnIsDisabled); //设置字段只读
            var fieldControlType = fieldControl.getControlType().toLowerCase();
            if (fieldControlType == "standard" && fieldControlType != "subgrid" && fieldControlType != "iframe") {
                var field = fieldControl.getAttribute();
                field.setValue(null); //置空字段的值
            }
        }
    }
}
/*设置指定选项卡(tab)下的所有字段是否只读,且置空字段的值(sectionControl:节控件对象 blnIsDisabled:设置是否只读[true:只读 false:可编辑])
如:var tabControl=Xrm.Page.ui.tabs.get("tab_general");
setTabFields(tabControl,10,true);
*/
function setTabFields(tabControl, setTypeCode, value) {
    if (tabControl.sections != null && tabControl.sections.get() != null && tabControl.sections.get().length > 0) {
        for (var i = 0; i < tabControl.sections.get().length; i++) {
            var sectionControl = tabControl.sections.get()[i];
            switch (setTypeCode) {
                case 10: //设置是否只读
                    setSectionFieldsStatus(sectionControl, value);
                    break;
                case 20: //置空字段的值
                    resetSectionFieldsValue(sectionControl);
                    break;
                case 30: //设置是否只读,且置空字段的值
                    setSectionFieldsStatusAndReset(sectionControl, value);
                    break;
            }
        }
    }
}
/*临时记录字段的值(一般在OnLoad和OnChange事件中调用):fieldName为CRM字段名,fieldValue为要设置的字段的值
如:var new_accountid = Xrm.Page.getAttribute("new_accountid");
setPreValueForField(new_accountid.getName(), new_accountid.getValue());
*/
function setPreValueForField(fieldName, fieldValue) {
    var pre_fieldname_valuecontrol = document.getElementById("pre_" + fieldName + "_value");
    if (pre_fieldname_valuecontrol != undefined && pre_fieldname_valuecontrol != null) {
        pre_fieldname_valuecontrol.value = fieldValue;
    } else {
        var fieldName_c = document.getElementById(fieldName + "_c");
        fieldName_c.innerHTML = fieldName_c.innerHTML + "<input type='hidden' id='pre_" + fieldName + "_value' value='" + fieldValue + "' />";
    }
}
/*获取字段的前一次录入的值:fieldName为CRM字段名
如:var new_accountid = Xrm.Page.getAttribute("new_accountid");
new_accountid.setValue(getPreValueForField(new_accountid.getName()));
*/
function getPreValueForField(fieldName) {
    var pre_fieldname_valuecontrol = document.getElementById("pre_" + fieldName + "_value");
    return pre_fieldname_valuecontrol.value;
}
/*验证电话号码的合法性
var telephoneNo="1234565890";
var blnIsTelNoValid=checkTelNoValidation(telephoneNo);
*/
function checkTelNoValidation(telephoneNo) {
    var reg_number = /^[0-9]\d*$/; //数字
    if (telephoneNo != null && !reg_number.exec(telephoneNo)) {
        return false;
    }
    return true;
}

var G_LIST_MULTI_LANG_TEXTS = null;
//初始化取得多语言数据
/*
查询自定义的多语言文本(languageCode:语言代码 purposeType:用途类型[10:脚本 20:插件 30:门户系统 40:自定义页面 50:自定义Web Service] 应用模块:applyModule)
iniMultiLangTexts(ODataPath,2052, 10 ,"account");

*/
function iniMultiLangTexts(_ODataPath, _languageCode, _purposeType, _applyModule) {
    var langText = "";
    if (_applyModule == "") {
        alert("多语言数据取得出错!When the multi-language data get, system error");
        return;
    }
    retrieveReq = getMultiLangTextList(_ODataPath, _languageCode, _purposeType, _applyModule);
    if (retrieveReq.statusText != "OK") {
        alert("多语言数据取得出错!When the multi-language data get, system error" + "(" + retrieveReq.response + ")");
        result = null;
        return "";
    } else {
        G_LIST_MULTI_LANG_TEXTS = new Object();
        for (var i = 0; i < retrieveReq.response.results.length; i++) {
            langText = retrieveReq.response.results[i];
            G_LIST_MULTI_LANG_TEXTS[langText.new_code] = langText.new_text;
        }
    }
}

//根据代码取得多语言
//初始化iniMultiLangTexts后,直接调用
//getMultiLangTexts("alert_new_system_err")
function getMultiLangTexts(_new_code) {
    var rtnvalue = "";
    if (G_LIST_MULTI_LANG_TEXTS != null) {
        rtnvalue = G_LIST_MULTI_LANG_TEXTS[_new_code];
    }
    return rtnvalue;
}

/*获取查找类型字段值的对象(适用于表单)
如:var entityReferent=getEntityReferenceObject(accountid,"account","CRM客户");
*/
function getEntityReferenceObject(id, entityType, name) {
    var lookupReference = [];
    lookupReference[0] = {};
    lookupReference[0].id = id;
    lookupReference[0].entityType = entityType;
    lookupReference[0].name = name;

    return lookupReference;
}

转自:http://www.cnblogs.com/allenhua/archive/2013/01/31/2888300.html

posted @ 2013-09-05 17:45  刘满意  阅读(2466)  评论(0编辑  收藏  举报