我是靠谱客的博主 现代飞机,最近开发中收集的这篇文章主要介绍dynamics crm 常用js,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

描述方法备注
获取当前记录的guidXrm.Page.data.entity.getId();
获取当前用户Xrm.Page.context.getUserId(); 
获取当前界面某个字段的值Xrm.Page.getAttribute("字段").getValue();
设置某个字段的值Xrm.Page.getAttribute("字段").setValue(value);
设置某个字段必填Xrm.Page.getAttribute("字段").setRequiredLevel("required");
界面上取消某个字段必填属性Xrm.Page.getAttribute("字段").setRequiredLevel("none");
datetime类型字段读取值var myContactBirthday;
myContactBirthday = Xrm.Page.getAttribute("birthdate").getValue();
alert("Contact birthday is: " + myContactBirthday);
var year = myContactBirthday.getFullYear();
var month = myContactBirthday.getMonth(); // from 0 to 11
var day = myContactBirthday.getDate(); // from 1 to 31
month = month + 1;
alert("Year: " + year + ", Month: " + month + ", Day: " + day);
时间类型字段赋值Xrm.Page.data.entity.attributes.get("new_status_category_date_detail").setValue(new Date())
设置某个tab隐藏Xrm.Page.ui.tabs.get("TAB名称").setVisible(false);
设置某个字段显示与隐藏Xrm.Page.getControl("字段").setDisabled(true);
界面上js控制阻止保存ExecutionObj.getEventArgs().preventDefault();//阻止保存操作
货币(currency)类型字段保存Xrm.Page.getAttribute("字段").setValue(parseFloat(具体值));
接口查询方式   var clientURL = Xrm.Page.context.getClientUrl();
        var req = new XMLHttpRequest();

        req.open("GET", encodeURI(clientURL + "/api/data/v9.1/cr15f_allowancelists?$select=_cr15f_allowancenamelookup_value,cr15f_allowance&$filter=_cr15f_allowanceno_value eq '" + guid + "'"), false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
            if (this.readyState == 4) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    var rdata = JSON.parse(this.responseText);
                  

                }
                else {
                    var error = JSON.parse(this.responseText).error;
                    Xrm.Utility.alertDialog("查询实体记录出错." + error.message);
                    result = false;
                }
            }
        };
        req.send();
日期类型字段求day差    var new_tender_estimated_date_detail = Date.parse(Xrm.Page.data.entity.attributes.get("new_tender_estimated_date_detail").getValue());   //预计投标日期
    var createdon = Date.parse(Xrm.Page.data.entity.attributes.get("createdon").getValue());   //商机创建日期
    var days = (new_tender_estimated_date_detail - createdon) / (1 * 24 * 60 * 60 * 1000);
界面上所有字段只读设置(循环遍历方式)            var controls = Xrm.Page.ui.controls.get();
            for (var i in controls) {
                var control = controls[i];
                control.setDisabled(true);
            }
查询当前记录的方法        var req = new XMLHttpRequest();
        req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/opportunities(" + entityId.toString().replace('{', '').replace('}', '') + ")", false);   //new_orders  要修改的表名
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if ((this.status == 204) || (this.status == 200)) {
                    Xrm.Utility.alertDialog("执行成功!");
                    console.log(this.responseText);
                }
                else {
                    Xrm.Utility.alertDialog(this.responseText);
                }
                Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId()); //刷新当前界面
            }
        };
        req.send(JSON.stringify(entity));
js调用workflow的方法function executeWorkflow(entityId, workflowId, clientUrl) {
    var clientURL = Xrm.Page.context.getClientUrl();   //获取当前客户端的url
    var req = new XMLHttpRequest()
    req.open("POST", encodeURI(clientURL + "/api/data/v9.0/workflows(" + workflowId + ")/Microsoft.Dynamics.CRM.ExecuteWorkflow"), true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            //Xrm.Utility.alertDialog(this.status);
            if ((this.status == 204) || (this.status == 200)) {
                Xrm.Utility.alertDialog("执行成功!");
                console.log(this.responseText);
            }
            else {
                Xrm.Utility.alertDialog("执行出错。");
                console.log(this.responseText);
            }
            Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId()); //刷新当前界面
        }
    };
    var requestMsg = {};
    var entityids = entityId.toString();
    requestMsg.EntityId = entityids;

    req.send(JSON.stringify(requestMsg));
}
js调用自定义api接口的方法                                var req4 = new XMLHttpRequest()
                                req4.open("post", "http://139.217.100.219:9001/api/Opportunity/GetOpportunity", false);
                                //req4.open("post", configvalue, false);
                                req4.setRequestHeader("Accept", "application/json");
                                req4.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                                req4.setRequestHeader("OData-MaxVersion", "4.0");
                                req4.setRequestHeader("OData-Version", "4.0");
                                req4.onreadystatechange = function () {
                                    if (this.readyState == 4) {
                                        if (this.status == 200 || this.status == 204) {
                                            var result = JSON.parse(this.responseText);
                                        }
                                        else {
                                            Xrm.Utility.alertDialog(this.responseText);
                                        }
                                    }
                                };
                                req4.send(JSON.stringify(entitys));
                            }
刷新当前打开的form窗体Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId()); //刷新当前界面
获取lookup类型字段function SetValue() {
    var state = new Array();
    state = Xrm.Page.getAttribute("parentaccountid").getValue();
    if (state != null) {
        var stateText = state[0].name;
        var stateId = state[0].id;
        var stateType = state[0].entityType;
        alert(stateType);
    }
}
lookup清空值var state = Xrm.Page.getAttribute("new_state");
if (state != null)
{
Xrm.Page.getAttribute("new_state").setValue(null);
}
lookup赋值var state = new Array();
state[0] = new Object();
state[0].id = "{BA0762E4-64D2-E111-909E-00155D6C871A}";
state[0].name = "New York";
state[0].entityType = "new_state";
Xrm.Page.getAttribute("new_state").setValue(state);
optionset类型字段读取值var sval = Xrm.Page.getAttribute("new_optionset").getSelectedOption().text;
var sval = Xrm.Page.getAttribute("new_optionset").getSelectedOption().value;
分别读取显示文本和值
另外,我们还可以用下面的方法来获取text和value:
var sval = Xrm.Page.getAttribute("new_optionset").getText();
var sval = Xrm.Page.getAttribute("new_optionset").getValue();
optionset类型字段赋值function SetOSValue(osName, osLabel)
{
var options = Xrm.Page.getAttribute(osName).getOptions();
for(i = 0; i < options.length; i++)
{
if (options[i].text == osLabel)
Xrm.Page.getAttribute(osName).setValue(options[i].value);
}
}
节隐藏Xrm.Page.ui.tabs.get("tab_5").sections.get("tab_5_section_1").setVisible(false);tab_5:选项卡
tab_5_section_1:节
标签隐藏Xrm.Page.ui.tabs.get("tab_5").setVisible(false);tab_5:选项卡

//判断用户是否具有某个角色

function RoleControlFields_lead()
{
    //获取用户的角色ID
    var roleIdArray = Xrm.Utility.getGlobalContext().userSettings.securityRoles;
    var roleIdFilter = "";
    roleIdArray.forEach(function (element) {
        roleIdFilter = roleIdFilter + "roleid eq " + element + " or ";
    });
    var roleOwner;

    //通过Web API返回用户拥有的角色名称
    var queryRoleName = "?$select=name&$filter=" + roleIdFilter.substring(0, roleIdFilter.length - 3);
    Xrm.WebApi.retrieveMultipleRecords("role", queryRoleName).then(
        function success(result) {
            //判断是否有HW 商务专员、HW 商务经理、HW 商机负责人的角色
            for (var i = 0; i < result.entities.length; i++) {
                if (result.entities[i]["name"] == "窗体部分字段显示(非华为)") {   //|| result.entities[i]["name"] == "HW 商务经理"
                    roleOwner = "X";
                }
            }
            SetFieldVisible_leadform(roleOwner);
        },
        function (error) {
            // handle error conditions           
        }
    );

}

//注册执行业务线的查找列表事件(绑定在窗体onload事件上)
function setBusinessLineFilter() {
    Xrm.Page.getControl("new_businessline").addPreSearch(function () {
        businessFilter("new_businessline", "new_businessgroup");
    });
}

//根据业务部门,角色名查询用户   -----webApi的其他使用方式
function setExecutivedeliverymanager(rolename, businessunitid, targetfieldname) {

    //用户 systemuser:systemuserid
    //角色 role:roleid
    //角色权限  systemuserroles:   systemuserid,roleid

    var fetchxml = "<fetch mapping='logical' version='1.0'>" +
        "<entity name='role' >" +
        "<filter>" +
        "<condition attribute='name' operator='eq' value='" + rolename + "' />" +
        "<condition attribute='businessunitid' operator='eq' value='" + businessunitid + "' />" +
        "</filter>" +
        "<link-entity name='systemuserroles' from='roleid' to='roleid' alias='b' link-type='inner'>" +
        "<attribute name='systemuserid' />" +
        "</link-entity>" +
        "</entity >" +
        "</fetch > ";
    var req = new XMLHttpRequest();
    req.open("GET", encodeURI(Xrm.Page.context.getClientUrl() + "/api/data/v9.0/roles?fetchXml=" + encodeURI(fetchxml), false));
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.onreadystatechange = function () {
        if (this.readyState == 4) {
            req.onreadystatechange = null;
            if ((this.status == 204) || (this.status == 200)) {
                if (JSON.parse(this.response).value.length > 0) {
                    var data = JSON.parse(this.response).value;
                    var systemuserid = data[0]["b.systemuserid"].toString();
                    //var arr = new Array();
                    //arr[0] = new Object();
                    //arr[0].id = "{" + systemuserid + "}";
                    //arr[0].name = "textValue";
                    //arr[0].entityType = "systemuser";
                    //Xrm.Page.getAttribute(targetfieldname).setValue(arr);

                    Xrm.WebApi.retrieveRecord("systemuser", systemuserid, "?$select=fullname").then(
                        function success(result) {
                            console.log("Retrieved values: Name: " + result.name + ", Revenue: " + result.revenue);
                            var arr = new Array();
                            arr[0] = new Object();
                            arr[0].id = "{" + systemuserid + "}";
                            arr[0].name = result.fullname;
                            arr[0].entityType = "systemuser";
                            Xrm.Page.getAttribute(targetfieldname).setValue(arr);
                        },
                        function (error) {
                            console.log(error.message);
                            // handle error conditions
                        }
                    );
                    //
                }
                else {
                    Xrm.Page.getAttribute("new_executivedeliverymanager").setValue(null);
                }
            }
            else {
                var error = JSON.parse(this.response).error;
            }
        }
    };
    req.send();

}

//执行各业务部门查找列表   ----webapi新的使用方式
function businessFilter(selectedFieldName, parentFieldName) {
    var businessUnitFilter;
    var parentFieldValue = Xrm.Page.getAttribute(parentFieldName).getValue();
    if (parentFieldValue != null) {
        if (selectedFieldName == "new_businessline") {
            businessUnitFilter = "<filter type='and'>"
                + "<condition attribute='parentbusinessunitid' operator='eq' value='" + parentFieldValue[0].id + "'/>"
                + "<condition attribute='name' operator='like' value='%业务线%' />"
                + "</filter>";
        }
        else {
            businessUnitFilter = "<filter type='and'>"
                + "<condition attribute='parentbusinessunitid' operator='eq' value='" + parentFieldValue[0].id + "'/>"
                + "</filter>";
        }
    }
    else {
        businessUnitFilter = "<filter type='and'>"
            + "<condition attribute='parentbusinessunitid' operator='eq' value='00000000-0000-0000-0000-000000000000'/>"
            + "</filter>"
    }

    Xrm.Page.getControl(selectedFieldName).addCustomFilter(businessUnitFilter, 'businessunit');
}

最后

以上就是现代飞机为你收集整理的dynamics crm 常用js的全部内容,希望文章能够帮你解决dynamics crm 常用js所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部