博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Microsoft Dynamics CRM 4.0 JScript 通用公共方法

Posted on 2013-08-30 21:06  Hamilton Tan  阅读(566)  评论(0编辑  收藏  举报

1.基本参数

var CRM_FORM_TYPE_CREATE = 1;
var CRM_FORM_TYPE_UPDATE = 2;
var CRM_FORM_TYPE_READ_ONLY = 3;
var CRM_FORM_TYPE_DISABLED = 4;
var CRM_FORM_TYPE_QUICK_CREATE = 5;
var CRM_FORM_TYPE_BULK_EDIT = 6;

2.基本方法

function FormSubmit(method, action) {
    var frm = $("#form1")[0];
    frm.method = method;
    frm.action = action;
    frm.submit();
}

3.CRM实体检索

RetrieveSingleEntity = function (entityName, entityId, columnSet) {
    var soapNS = "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"";
    var xsiNS = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
    var xsdNS = "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";
    var defaultNS = "xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\"";
    var queryNS = "xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\"";

    var async = false;
    var sMessage = BuildStart() + BuildBody(entityName, entityId, columnSet) + BuildEnd();

    var oHttp = new ActiveXObject("Msxml2.XMLHTTP");

    SendMessage(oHttp);
    return BuildResult(oHttp);

    function SendMessage(oHttp) {
        var url = "/mscrmservices/2007/crmservice.asmx";
        oHttp.open("POST", url, async);
        oHttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
        oHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        oHttp.setRequestHeader("Content-Length", sMessage.length);

        oHttp.Send(sMessage);
    }

    function BuildResult(oHttp) {
        var response = oHttp.responseText;
        var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
        xmlDoc.async = async;
        xmlDoc.loadXML(response);
        if (xmlDoc.parseError.errorCode != 0) {
            var xmlErr = xmlDoc.parseError;
            alert("Error retrieving Recipient: " + xmlErr.reason);
        }
        else {
            var arrResult = new Array();
            var returnNode = xmlDoc.documentElement.selectSingleNode("/soap:Envelope/soap:Body/ExecuteResponse/Response/BusinessEntity/Properties");
            for (var i = 0; i < returnNode.childNodes.length; i++) {
                arrResult[i] = new Array();
                arrResult[i][0] = returnNode.childNodes[i].attributes[1].value;
                arrResult[i][1] = returnNode.childNodes[i].text;
                if (returnNode.childNodes[i].attributes[0].value == "PicklistProperty") {
                    if (returnNode.childNodes[i].childNodes[0].attributes[0] != undefined) {
                        arrResult[i][2] = returnNode.childNodes[i].childNodes[0].attributes[0].value;
                    }
                }
                if (returnNode.childNodes[i].attributes[0].value == "LookupProperty" || returnNode.childNodes[i].attributes[0].value == "OwnerProperty" || returnNode.childNodes[i].attributes[0].value == "CustomerProperty") {
                    if (returnNode.childNodes[i].childNodes[0].attributes[0] != undefined) {
                        if (returnNode.childNodes[i].childNodes[0].attributes[0].name == "name") {
                            arrResult[i][2] = returnNode.childNodes[i].childNodes[0].attributes[0].value;
                        }else {
                            arrResult[i][2] = null;
                        }
                        if (returnNode.childNodes[i].childNodes[0].attributes[0].name == "type") {
                            arrResult[i][3] = returnNode.childNodes[i].childNodes[0].attributes[0].value;
                        }
                        if (returnNode.childNodes[i].childNodes[0].attributes[1] != undefined) {
                            if (returnNode.childNodes[i].childNodes[0].attributes[1].name == "type") {
                                arrResult[i][3] = returnNode.childNodes[i].childNodes[0].attributes[1].value;
                            }
                        }
                    }
                }
            }
        }
        return arrResult;
    }
    function BuildStart() {
        var sMessage = "";

        sMessage += "<soap:Envelope ";
        sMessage += soapNS + " ";
        sMessage += xsiNS + " ";
        sMessage += xsdNS + ">";
        sMessage += GenerateAuthenticationHeader();

        return sMessage;
    }

    function BuildBody(entityName, entityId, columnSet) {
        var sMessage = "";

        sMessage += "<soap:Body>";
        sMessage += "<Execute " + defaultNS + ">";
        sMessage += "<Request xsi:type=\"RetrieveRequest\" ReturnDynamicEntities=\"true\">";
        sMessage += "<OptionalParameters>";
        sMessage += "<OptionalParameter xsi:nil=\"true\" />";
        sMessage += "</OptionalParameters>";
        sMessage += "<Target xsi:type=\"TargetRetrieveDynamic\">";
        sMessage += "<EntityName>" + entityName + "</EntityName>";
        sMessage += "<EntityId>" + entityId + "</EntityId>";
        sMessage += "</Target>";
        if (columnSet == null || columnSet.length == 0) {
            sMessage += "<ColumnSet " + queryNS + " xsi:type=\"q1:AllColumns\" />";
        }
        else {
            sMessage += "<ColumnSet " + queryNS + " xsi:type=\"q1:ColumnSet\">";
            sMessage += "<q1:Attributes>";
            for (var i = 0; i < columnSet.length; i++) {
                sMessage += "<q1:Attribute>";
                sMessage += columnSet[i];
                sMessage += "</q1:Attribute>";
            }
            sMessage += "</q1:Attributes>";
            sMessage += "</ColumnSet>";
        }
        sMessage += "</Request>";
        sMessage += "</Execute>";
        sMessage += "</soap:Body>";

        return sMessage;
    }

    function BuildEnd() {
        return "</soap:Envelope>";
    }
}

4.获取lookup类型的值

GetLookupFieldValue = function (oResult, fieldScheduleName) {
    for (var i = 0; i < oResult.length; i++) {
        if (oResult[i] == undefined) {
            continue;
        }
        if (oResult[i][0] == undefined) {
            continue;
        }
        if (oResult[i][0] == fieldScheduleName) {
            var item = new Object();
            item.id = oResult[i][1];
            item.name = oResult[i][2];
            item.typename = oResult[i][3];
            var data = new Array();
            data[0] = item;
            break;
        }
    }
    return data;
}

5.获取picklist类型的值

GetPicklistFieldValue = function (oResult, fieldScheduleName) {
    for (var i = 0; i < oResult.length; i++) {
        if (oResult[i] == undefined) {
            continue;
        }
        if (oResult[i][0] == undefined) {
            continue;
        }
        if (oResult[i][0] == fieldScheduleName) {
            var item = new Object();
            item.value = oResult[i][1];
            item.selectedtext = oResult[i][2];
            var data = new Array();
            data[0] = item;
            break;
        }
    }
    return data;
}

6.获取字段的值

GetFieldValue = function (oResult, fieldScheduleName) {
    var fieldValue;
    for (var i = 0; i < oResult.length; i++) {
        if (oResult[i] == undefined) {
            continue;
        }
        if (oResult[i][0] == undefined) {
            continue;
        }
        if (oResult[i][0] == fieldScheduleName) {
            fieldValue = oResult[i][1];
            break;
        }
    }
    return fieldValue;
}

7.获取当前的用户

GetCurrentUserId = function () {
    var soapBody = "<soap:Body><Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'><Request xsi:type='WhoAmIRequest' /></Execute></soap:Body>";

    var soapXml = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>";
    //    var header1 = GenerateAuthenticationHeader();
    var header1 = "<soap:Header><CrmAuthenticationToken xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "<AuthenticationType xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">0</AuthenticationType>" +
    "<CrmTicket xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\"></CrmTicket>" +
    "<OrganizationName xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">LOVOL</OrganizationName>" +
    "<CallerId xmlns=\"http://schemas.microsoft.com/crm/2007/CoreTypes\">00000000-0000-0000-0000-000000000000</CallerId>" +
    "</CrmAuthenticationToken></soap:Header>";
    soapXml += header1;
    soapXml += soapBody;
    soapXml += "</soap:Envelope>";

    var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlhttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
    xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
    xmlhttp.send(soapXml);

    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(xmlhttp.responseXML.xml);
    CRMUserGuid = xmlDoc.getElementsByTagName("UserId")[0].childNodes[0].nodeValue;
    return CRMUserGuid;
}

//注意:这个获取的值是小写,一般可以通过下面的方式处理下。
var currentUserId = ("{" + GetCurrentUserId() + "}").toUpperCase();//获取当前用户的GUID

8.CRM实体筛选

RetrieveQueryRecords = function (fetchXmlStr) {
    var returnResults = null;
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    GenerateAuthenticationHeader() +
    "<soap:Body>" +
    "<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<fetchXml>" +
    fetchXmlStr +
    "</fetchXml>" +
    "</Fetch>" +
    "</soap:Body>" +
    "</soap:Envelope>";

    var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
    xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
    xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xHReq.setRequestHeader("Content-Length", xml.length);
    xHReq.send(xml);

    var resultXml = xHReq.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert(msg);
    }
    else {
        var resultSet = new String();
        resultSet = resultXml.text;
        resultSet.replace('&lt;', '<');
        resultSet.replace('&gt;', '>');
        var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        oXmlDoc.async = false;
        oXmlDoc.loadXML(resultSet);
        returnResults = oXmlDoc.getElementsByTagName('result');
    }
    return returnResults;
}

9.设置IFrame控件(IFrame控件名称,关联关系名称)

SetIFameSrc = function (oIFrame, relationName) {
    areaIframe_OnReadyStateChange = function () {
        if (oIFrame.readyState == "complete") {
            var tableList = oIFrame.contentWindow.document.getElementsByTagName("table");
            if (tableList != null) {
                for (var i = 0; i < tableList.length; i++) {
                    if (tableList[i].className == "ms-crm-Form-Area") {
                        tableList[i].style.paddingBottom = 0;
                        tableList[i].style.paddingLeft = 0;
                        tableList[i].style.paddingRight = 0;
                        break;
                    }
                }
            }
        }
    }
    oIFrame.attachEvent("onreadystatechange", areaIframe_OnReadyStateChange);

    var sArea = relationName;
    var sBaseUrl = "areas.aspx?";
    var html = sBaseUrl;
    html += "oId=" + crmForm.ObjectId;
    html += "&oType=" + crmForm.ObjectTypeCode;
    html += "&security=" + crmFormSubmit.crmFormSubmitSecurity.value;
    html += "&roleOrd=1";
    html += "&tabSet=" + sArea;
    oIFrame.src = html;
}

10.判断当前登录用户是否存在安全角色权限(输入角色名)

ChectUserRoles = function (roleName) {
    var checkValue = false;
    var xmlRoleCount = "&lt;fetch mapping=\'logical\' count=\'50\' aggregate=\'true\'&gt;" +
                            "&lt;entity name=\'systemuserroles\'&gt;" +
                                "&lt;attribute name=\'systemuserroleid\' aggregate=\'count\' alias=\'count\' /&gt;" +
                                "&lt;filter&gt;" +
                                    "&lt;condition attribute=\'systemuserid\' operator=\'eq\' value=\'" + guidCurrentUserId + "\' /&gt;" +
                                "&lt;/filter&gt;" +
                                "&lt;link-entity name=\'role\' from=\'roleid\' to=\'roleid\' link-type=\'inner\'&gt;" +
                                    "&lt;filter&gt;" +
                                        "&lt;condition attribute=\'name\' operator=\'eq\' value=\'" + roleName + "\' /&gt;" +
                                    "&lt;/filter&gt;" +
                                "&lt;/link-entity&gt;" +
                            "&lt;/entity&gt;" +
                        "&lt;/fetch&gt;";
    resultRoleCount = RetrieveQueryRecords(xmlRoleCount);
    if (resultRoleCount[0] != null) {
        if (resultRoleCount[0].selectSingleNode('./count').nodeTypedValue > 0) {
            checkValue = true;
        }
    }
    return checkValue;
}

11.隐藏"文件菜单(F)"、"保存"、"保存并关闭"、"保存并新建"三个按钮

HideSaveButtonGroup = function () {
    var file = document.getElementById("file"); //文件菜单(F)
    var _MBcrmFormSave = document.getElementById("_MBcrmFormSave"); //保存
    var _MBcrmFormSaveAndClose = document.getElementById("_MBcrmFormSaveAndClose"); //保存并关闭
    var _MBcrmFormSubmitCrmForm59truetruefalse = document.getElementById("_MBcrmFormSubmitCrmForm59truetruefalse"); //保存并新建

    file.style.display = "none";
    _MBcrmFormSave.style.display = "none";
    _MBcrmFormSaveAndClose.style.display = "none";
    _MBcrmFormSubmitCrmForm59truetruefalse.style.display = "none";
}

12.添加保存并新建

AddSaveandCreate = function () {
    var _MBcrmFormSubmitCrmForm59truetruefalse = window.document.getElementById("_MBcrmFormSubmitCrmForm59truetruefalse");
    var a = _MBcrmFormSubmitCrmForm59truetruefalse.getElementsByTagName("a");
    if (a.length > 0) {
        a[0].innerHTML = "<img tabIndex='0' class='ms-crm-Menu-ButtonFirst' alt='保存并新建' src='/_imgs/ico/16_L_saveOpen.gif'/>"
        a[0].innerHTML += "<span tabIndex='0' class='ms-crm-MenuItem-TextRTL'>保存并新建</span>";
    }
}

13.禁用lookUp查看事件

DisableLookup = function (item) {
    var item = window.document.getElementById(item);
    var spanlist = item.getElementsByTagName("span");
    for (var i = 0; i < spanlist.length; i++) {
        if (spanlist[i].onclick = "openlui()") {
            spanlist[i].onclick = "";
        }
    }
}

14.隐藏字段

HideField = function (fieldName) {
    var crmform_field_c = document.getElementById(fieldName + "_c");
    var crmform_field_d = document.getElementById(fieldName + "_d");
    crmform_field_c.style.display = "none";
    crmform_field_d.style.display = "none";
}

15.隐藏IFrame中工具栏上的部分按钮

function HideFrameGridBarItems() {
    var frame = event.srcElement;
    if (frame.readyState != "complete")
        return;
    var window = frame.contentWindow;
    var mnuBar1 = window.document.getElementById("mnuBar1");
    var mnuBar1_UL = mnuBar1.getElementsByTagName("ul");
    var mnuBar1_LIs = mnuBar1.getElementsByTagName("li");
    if (mnuBar1_LIs != null && mnuBar1_LIs.length > 0) {
        for (var i = 0; i < mnuBar1_LIs.length; i++) {
            if (mnuBar1_LIs[i].id != "_MBcrmGridPrint" && mnuBar1_LIs[i].id != "_MBcrmGridPrint" && mnuBar1_LIs[i].id != "_MBcrmGridExportToExcel") {
                mnuBar1_LIs[i].style.display = "none";
            }
        }
    }
}

16.禁用所有控件,并隐藏部分控件

DisabledAllControls = function () {
    var allFormControls = crmForm.all;
    for (var i = 0; i < allFormControls.length; i++) {
        var singleControl = allFormControls[i];
        if (singleControl.id != null && singleControl.id != "") {
            singleControl.Disabled = true;
        }
    }
}

17.读取脚本文件

function load_script(url) {
    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('GET', url, false);
    xmlHTTPRequest.send('');
    eval(xmlHTTPRequest.responseText);
    var s = xmlHTTPRequest.responseText.split(/\n/);
    var r = /^(?:function|var)\s*([a-zA-Z_]+)/i;
    for (var i = 0; i < s.length; i++) {
        var m = r.exec(s[i]);
        if (m != null) {
            window[m[1]] = eval(m[1]);
        }
    }
}

18.获取当前时间 

//获取当前时间 格式为2013/8/30
getCurrenTime = function () {
    var d, currentTime = "";
    d = new Date();
    currentTime += d.getYear() + "/";
    currentTime += (d.getMonth() + 1) + "/";
    currentTime += d.getDate();
    return currentTime;
}

//获取当前详细时间 格式为2013/8/30 14:55:30
getCurrentTime = function () {
    var d, currentTime = "";
    d = new Date();
    currentTime += d.getYear() + "/";
    currentTime += (d.getMonth() + 1) + "/";
    currentTime += d.getDate() + " ";
    currentTime += d.getHours() + ":";
    currentTime += d.getMinutes() + ":";
    currentTime += d.getSeconds();
    return currentTime;
}

19.获取服务器时间 

crmForm.all.new_timespan.DataValue = new Date("2013/01/01");
crmForm.all.字段名.DataValue = new Date("2013-01-01");//会报错
//需要replace(/-/g, "/");替换下

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;
}
GetServerDateTime = function() {
    var returnValue = null;
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    GenerateAuthenticationHeader() +
    "<soap:Body>" +
    "<GetServerTime xmlns='http://Www.Frensworkz.Com.Crm40.WebService/' />" +
    "</soap:Body>" +
    "</soap:Envelope>";

    var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
    xHReq.Open("POST", "/ISV/ExtensionWebService/GetServerTimeService.asmx", false);
    xHReq.setRequestHeader("SOAPAction", "http://Www.Frensworkz.Com.Crm40.WebService/GetServerTime");
    xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xHReq.setRequestHeader("Content-Length", xml.length);
    xHReq.send(xml);

    var resultXml = xHReq.responseXML;
    var errorCount = resultXml.selectNodes('//error').length;
    if (errorCount != 0) {
        var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
        alert(msg);
    }
    else {
        returnValue = new Date(Date.parse(resultXml.text.replace(/-/g, "/")));
    }
    return returnValue;
}
getAddDate = function (dateValue, dateType, addValue) {
    var year = dateValue.getYear();
    var month = dateValue.getMonth();
    var day = dateValue.getDate();
    if (dateType == "year") {
        year = parseInt(year) + parseInt(addValue);
    }
    if (dateType == "month") {
        month = parseInt(month) + parseInt(addValue);
    }
    if (dateType == "day") {
        day = parseInt(day) + parseInt(addValue);
    }
    var newDate = Date.parse(year + "-" + month + "-" + day);
    return newDate;
}

20.其他

var new_returnrepairbutton_d = document.getElementById("new_returnrepairbutton_d");//返修按钮
new_returnrepairbutton_d.style.display='none';
//显示返修按钮
new_returnrepairbutton_d.innerHTML = "<button class='ms-crm-Button' id='returnRepairBtn' type='button' onclick='SubmitOperate();'>返修</button>";


   
//隐藏明细工具栏
var frame = document.getElementById("IFRAME_Details");
frame.attachEvent("onreadystatechange", HideFrameGridBarItems);

//about: blank

var CRM_FORM_TYPE_UPDATE = 2;
//添加IFRAME销售合同明细
if (crmForm.FormType == CRM_FORM_TYPE_UPDATE) {
    var IFrameSalesContractDetails = crmForm.all.IFRAME_SalesContractDetails;
    SetIFameSrc(IFrameSalesContractDetails, "new_sales_contract_new_sales_contract_detail");
}

//过滤只能选择状态new_status为已审批的(30)和已接受(40)的信息  
var new_procurement_planid = crmForm.all.new_procurement_planid;//信息编号
fetchProcurementPlan = function () {
    var xmlProcurementPlan = "search=<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\">" +
                                    "<entity name=\"new_procurement_plan\">" +
                                        "<filter>" +
                                               "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" />" +
                                                "<condition attribute=\"new_name\" operator=\"like\" value=\"%%\"/>" +
                                               "<condition attribute=\"new_status\" operator=\"in\">" +
                                               "<value>30</value>" +
                                               "<value>40</value>" +
                                               "</condition>" +
                                         "</filter>" +
                                    "</entity>" +
                                "</fetch>";
    new_procurement_planid.additionalparams = xmlProcurementPlan;
    //new_procurement_planid.lookupbrowse = 1;//禁用搜索框
}

var xmlVehicle = "search=<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\">" +
                                   "<entity name=\"new_vehicle\">" +
                                       "<filter>" +
                                              "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" />" +
                                              "<condition attribute=\"new_status\" operator=\"eq\" value=\"10\" />" +
                                              "<condition attribute=\"new_ship_apply\" operator=\"eq\" value=\"null\" />" +
                                        "</filter>" +
                                        "<link-entity name=\"new_procurement_plan\" to=\"new_procurement_planid\" from=\"new_procurement_planid\" alias=\"b\" link-type=\"inner\">" +
                                            "<filter>" +
                                              "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" />" +
                                              "<condition attribute=\"new_billtype\" operator=\"eq\" value=\"1\" />" +
                                            "</filter>" +
                                        "</link-entity>" +
                                   "</entity>" +
                               "</fetch>";

var new_da_reason = crmForm.all.new_da_reason;
if (new_da_reason.DataValue == 0) {
    if (new_fail_reason.DataValue == null || new_fail_reason.DataValue == "") {
        alert('请填写未通过原因!');
        event.returnValue = false;
        return false;
    }
}

// "<condition attribute=\"new_order_status\" operator=\"null\"  />" +
//"<condition attribute=\"new_product_fourthid\" operator=\"eq\" value=\"\" />";
if (new_order.DataValue != null) {
    xmlSwivelmxzx += "<condition attribute=\"new_order\" operator=\"eq\" value='" + new_order.DataValue[0].id + "'/>";
} else {
    xmlSwivelmxzx += "<condition attribute=\"new_order\" operator=\"eq\" value=\"\" />";
}

if (new_order.DataValue != null) {
    xmlSwivelmxzx += "<condition attribute=\"new_order\" operator=\"eq\" value='" + new_order.DataValue[0].id + "'/>" ;
} else {
    xmlSwivelmxzx += "<condition attribute=\"new_order\" operator=\"null\"/>";
}


/*币种赋初始值*/
var transactioncurrencyid = crmForm.all.transactioncurrencyid; //币种
var transactioncurrencylookup = new Array();
var lookupItem = new Object();
lookupItem.name = "US Dollar";
lookupItem.id = "A4419C79-BB1B-E111-88C2-001CC497CFFC";
lookupItem.typename = "transactioncurrency";
transactioncurrencylookup[0] = lookupItem;
transactioncurrencyid.DataValue = transactioncurrencylookup;
/*币种赋初始值*/


//查询是否重复提交单据
function HaveSameRecord() {
    var returnValue = 0;
    var FetchXmlStr = "&lt;fetch mapping='logical' aggregate='true'&gt;" +
                "&lt;entity name='new_delivery_arrival'&gt;" +
                "   &lt;attribute name='new_delivery_arrivalid' aggregate='count' alias='HaveRows' /&gt;" +
                "   &lt;filter&gt;" +
                "       &lt;condition attribute='statecode' operator='eq' value='0' /&gt;" +
                "       &lt;condition attribute='new_vin' operator='eq' value='" + new_vin.DataValue[0].id + "' /&gt;" +
                "       &lt;condition attribute='new_status' operator='ne' value='10' /&gt;" +
                "   &lt;/filter&gt;" +
                "&lt;/entity&gt;" +
                "&lt;/fetch&gt;";
    var results = RetrieveQueryRecords(FetchXmlStr);
    returnValue = results[0].selectSingleNode('./HaveRows').nodeTypedValue;
    return returnValue;
}

var new_accpect_date = crmForm.all.new_accpect_date;    //验收日期
if (new_accpect_date.DataValue > new Date()) {
    alert('验收日期不得晚于当天的日期!');
    new_accpect_date.DataValue = null;
}



//金额大写转换
function Chinese(num) {
    if (!/^\d*(\.\d*)?$/.test(num)) throw (new Error(-1, "Number is wrong!"));
    var AA = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
    var BB = new Array("", "拾", "佰", "仟", "萬", "億", "圆", "");
    var CC = new Array("角", "分", "厘");
    var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = "";
    for (var i = a[0].length - 1; i >= 0; i--) {
        switch (k) {
            case 0: re = BB[7] + re; break;
            case 4: if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
                re = BB[4] + re; break;
            case 8: re = BB[5] + re; BB[7] = BB[5]; k = 0; break;
        }
        if (k % 4 == 2 && a[0].charAt(i) == "0" && a[0].charAt(i + 2) != "0") re = AA[0] + re;
        if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; k++;
    }

    if (a.length > 1) {
        re += BB[6];
        for (var i = 0; i < a[1].length; i++) {
            re += AA[a[1].charAt(i)] + CC[i];
            if (i == 2) break;
        }
        if (a[1].charAt(0) == "0" && a[1].charAt(1) == "0") {
            re += "元整";
        }
    } else {
        re += "元整";
    }
    if (re == "元整") re = "零元整";
    return re;
}


//显示字段
DisplayField = function (fieldName) {
    var crmform_field_c = document.getElementById(fieldName + "_c");
    var crmform_field_d = document.getElementById(fieldName + "_d");
    crmform_field_c.style.display = "block";
    crmform_field_d.style.display = "block";
}
//隐藏字段 HideField("new_cost_price");
HideField = function (fieldName) {
    var crmform_field_c = document.getElementById(fieldName + "_c");
    var crmform_field_d = document.getElementById(fieldName + "_d");
    crmform_field_c.style.display = "none";
    crmform_field_d.style.display = "none";
}

//验证是否有相关字段级控制角色的权限
function HaveControlFieldRole(RoleName) {
    var returnValue = 0;
    var FetchXmlStr = "&lt;fetch mapping='logical' aggregate='true'&gt;" +
                "&lt;entity name='new_controlfield_user'&gt;" +
                "   &lt;attribute name='new_controlfield_userid' aggregate='count' alias='HaveRows' /&gt;" +
                "   &lt;filter&gt;" +
                "       &lt;condition attribute='statecode' operator='eq' value='0' /&gt;" +
                "       &lt;condition attribute='new_systemuserid' operator='eq-userid' /&gt;" +
                "   &lt;/filter&gt;" +
                "   &lt;link-entity name='new_controlfield_role' from='new_controlfield_roleid' to='new_controlfield_roleid' link-type='inner' &gt;" +
                "       &lt;filter&gt;" +
                "           &lt;condition attribute='new_name' operator='eq' value='" + RoleName + "' /&gt;" +
                "       &lt;/filter&gt;" +
                "   &lt;/link-entity&gt;" +
                "&lt;/entity&gt;" +
                "&lt;/fetch&gt;";
    var results = RetrieveQueryRecords(FetchXmlStr);
    returnValue = results[0].selectSingleNode('./HaveRows').nodeTypedValue;
    return returnValue;
}

var XGCostPrice = HaveControlFieldRole("物料-标准价格-修改");

if (ZDCostPrice <= 0) {
    HideField("new_cost_price");
}

//隐藏销售模块
HideSalesModel = function () {
    var section = $(".ms-crm-Form-Section");
    if (section != null && section.length > 0) {
        for (var i = 0; i < section.length; i++) {
            if (section[i].innerText == "销售模块") {
                section[i].style.display = 'none';
                if (section[i] != null
                    && section[i].parentNode != null
                    && section[i].parentNode.parentNode != null
                    && section[i].parentNode.parentNode.parentNode != null) {
                    section[i].parentNode.parentNode.parentNode.style.display = 'none';
                }
            }
        }
    }
}

21.另外:

查询IFORM的方法    
    var totalMon = 0;    
    try {    
        var pageInfo = new PageInfo(1, 10000);  //分页参数    
        var orderArray = new Array(new OrderExpression("new_exp_undertakerid", ORDER_DIRECTION.Ascending)); //根据参数1排序    
        var attributesArray = new Array("new_pe_undertaker", "statecode"); //查询条件    
        var valuesArray = new Array(crmForm.ObjectId, "Active");//条件的值    
        var columnSetArray = new Array("new_money_undertaker");//要查询的列    
        var queryByAttribute = new QueryByAttribute("new_exp_undertaker", attributesArray, valuesArray, columnSetArray, pageInfo, orderArray);//参数一为实体名    
        var crmService = new CrmServiceAccelerator();    
        var entityCollection = crmService.RetrieveMultipleQueryByAttribute(queryByAttribute);    
        for (var i = 0; i < entityCollection.Entities.length; i++) {    
            var entity = entityCollection.Entities[i];    
            var amountProperty = entity.GetProperty("new_money_undertaker"); //获得值    
            if (amountProperty != null) {    
                totalMon += parseFloat(amountProperty.Value);    
            }    
        }    
    }    
    catch (error) {    
    }    
    return totalMon;    
    
设置Iframe    
function SetIFameSrc() {    
    var sArea = "new_move_library_single_new_move_library_";    
    var sBaseUrl = "areas.aspx?";    
    var html = sBaseUrl;    
    html += "oId=" + crmForm.ObjectId;    
    html += "&oType=" + crmForm.ObjectTypeCode;    
    html += "&security=" + crmFormSubmit.crmFormSubmitSecurity.value;    
    html += "&roleOrd=1";    
    html += "&tabSet=" + sArea;    
    IFRAME_movestoreroom.src = html;    
}    
筛选lookup字段    
 var fetchXmlStr = "search=<fetch  version='1.0' output-format='xml-platform' mapping='logical'><entity name='new_purchase_storage'>" +    
    "<filter><condition attribute='new_status' operator='eq' value='2' /><condition attribute='new_name' operator='like' value='%%'/>" +    
    "</filter></entity></fetch>"    
    new_purchase_storage.additionalparams = fetchXmlStr;    
    
根据ID查询单条记录    
var crmService=new CrmServiceAccelerator();    
var columns=new Array("new_name");    
var retEntity=crmService.Retrieve("new_unitofmeasurecode", itemUnit.Value, columns);    
var unitProperty=retEntity.GetProperty("new_name");    
if (unitProperty!=null)    
{    
    var salesorderLookup=new Array();
    var LookupItem=new Object();
    LookupItem.name=unitProperty.Value;
    LookupItem.id=itemUnit.Value;
    LookupItem.typename="new_unitofmeasurecode";
    salesorderLookup[0]=LookupItem;
    crmForm.all.new_unitofmeasurecodeid.DataValue=salesorderLookup;
}    
    
插入按钮    
var td_buttons = document.getElementById("new_button_submit_d");    
    
OnClickSubmit = function() {    
var ok = window.confirm("你确定该移库单进行过账?");    
if (ok) {    
    new_status.DataValue = 2;    
    new_status.ForceSubmit = true;    
    crmForm.Save();    
     }    
}    
//点击"过帐按钮"时触发    
OnClickPost = function() {    
    new_status.DataValue = 3;    
    new_status.ForceSubmit = true;    
    crmForm.Save();    
}    
td_buttons.innerHTML = "<button class='ms-crm-Button' id='btnSubmit' type='button' disabled='disabled'>提交</button>&nbsp;&nbsp;&nbsp;<button class='ms-crm-Button' id='btnPost' type='button' disabled='disabled'>过账</button>";    

 22.按条件查询多行,自定义实体

按条件查询多行,自定义实体
function getCurrentUserName(){
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
authenticationHeader +
" <soap:Body>" +
" <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <Request xsi:type=\"RetrieveMultipleRequest\" ReturnDynamicEntities=\"true\">" +
" <Query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>systemuser</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>fullname</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>EqualUserId</q1:Operator>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:Criteria>" +
" </Query>" +
" </Request>" +
" </Execute>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", SERVICE_PATH, false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;

var doc = xmlHttpRequest.responseXML;

return resultXml.selectSingleNode("//Property[@Name='fullname']/Value").nodeTypedValue;

}


function retrieve(entityName,entityId,attributeName){
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
authenticationHeader+
" <soap:Body>" +
" <Retrieve xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <entityName>"+entityName+"</entityName>" +
" <id>"+entityId+"</id>" +
" <columnSet xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>"+attributeName+"</q1:Attribute>" +
" </q1:Attributes>" +
" </columnSet>" +
" </Retrieve>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", SERVICE_PATH, false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
return resultXml;
}

function getAttribute(entityName,entityId,attribute){
var resultXml= retrieve(entityName,entityId,attribute);

//Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
//Display the retrieved value.
else
{
return resultXml.selectSingleNode("//q1:"+attribute).nodeTypedValue;
}
}


function retrieveByCondition(entityName,attribute_get,attributeName_con1,attributeValue_con1,attributeName_con2,attributeValue_con2){
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
authenticationHeader +
" <soap:Body>" +
" <Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <Request xsi:type=\"RetrieveMultipleRequest\" ReturnDynamicEntities=\"true\">" +
" <Query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>"+entityName+"</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>"+attribute_get+"</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>"+attributeName_con1+"</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">"+attributeValue_con1+"</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" <q1:Condition>" +
" <q1:AttributeName>"+attributeName_con2+"</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">"+attributeValue_con2+"</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:Criteria>" +
" </Query>" +
" </Request>" +
" </Execute>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

xmlHttpRequest.Open("POST", SERVICE_PATH, false);
xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Execute");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
return resultXml;
}
function getAttributeByCondition(entityName,attribute_get,attributeName_con1,attributeValue_con1,attributeName_con2,attributeValue_con2){
var resultXml= retrieveByCondition(entityName,attribute_get,attributeName_con1,attributeValue_con1,attributeName_con2,attributeValue_con2);

//Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0)
{
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
}
//Display the retrieved value.
else
{
//return resultXml;
return resultXml.selectSingleNode("//Property[@Name='"+attribute_get+"']/Value").nodeTypedValue;
}
}


//工作周报
var lookupItem= crmForm.all.new_projectweekreportid.DataValue;
if (lookupItem[0] != null)
{
//alert(lookupItem[0].name);
var currentUserName=getCurrentUserName();
var weekReportId=lookupItem[0].id;
var projectId= getAttribute("new_projectweekreport",weekReportId,"new_project2id");
var memberId=getAttributeByCondition("new_prejectmember","new_prejectmemberid","new_project2id",projectId,"new_name",currentUserName);
if(memberId != null){
//Create an array to set as the DataValue for the lookup control.
var lookupData = new Array();
//Create an Object add to the array.
var lookupItem= new Object();
//Set the id, typename, and name properties to the object.
lookupItem.id = memberId;
lookupItem.name=currentUserName;
lookupItem.typename = 'new_prejectmember';

// Add the object to the array.
lookupData[0] = lookupItem;
// Set the value of the lookup field to the value of the array.
crmForm.all.new_prejectmemberid.DataValue= lookupData;

}
}

23.IFAME

放出IFAME    
if(crmForm.FormType != 1 && crmForm.FormType != 5)    
{     
    var sArea ="new_new_kaohe_threeshow_new_threeshow_detail"; 
    var Url = "areas.aspx?"; 
    var html =Url; 
    html += "oId=" + crmForm.ObjectId; 
    html += "&oType=" + crmForm.ObjectTypeCode; 
    html += "&security=" + crmFormSubmit.crmFormSubmitSecurity.value;
    html += "&tabSet=" + sArea; 
    crmForm.all.IFRAME_threeshow_detail.src=html; 
}


隐藏IFAME工具条上按钮                        
var frame_m = crmForm.all.IFRAME_threeshow_detail;                        
    frame_m.attachEvent("onload", HideFrameGridBarItems);                    
                        
//隐藏IFARM工具栏按钮                        
function HideFrameGridBarItems() {                        
    var frame = event.srcElement;                        
    if (frame.readyState != "complete")                        
        return;                        
    var window = frame.contentWindow;                        
    DoHideFrameGridBarItem(window, "_MBlocAddRelatedToNonForm");                        
    DoHideFrameGridBarItem(window, "ISV_New");                        
    DoHideFrameGridBarItem(window, "_MBlocAddRelatedToNonForm");                        
    DoHideFrameGridBarItem(window, "_MBtoplocAssocOneToMany");                        
    DoHideFrameGridBarItem(window, "MoreActions");                        
    DoHideFrameGridBarItem(window, "assign");                        
    DoHideFrameGridBarItem(window, "delete");                        
}                        
function DoHideFrameGridBarItem(window, itemName) {                        
    var itemList = window.document.getElementsByTagName("LI");                        
    for (var i = 0; i < itemList.length; i++) {                        
        if (itemList[i].id == null)                        
            continue;                        
        if (itemList[i].id.indexOf(itemName) != -1) {                        
            itemList[i].style.visibility = "hidden";                        
            itemList[i].style.display = "none";                        
        }                        
    }                        
}