Dynamics CRM 常用 JS 方法集合
JS部分
拿到字段的值
var value= Xrm.Page.getAttribute("attributename").getValue();
Xrm.Page.getAttribute("attributename").setValue(value);
操作lookup字段值
//Get a lookup value
var lookup = new Array();
lookup = Xrm.Page.getAttribute("attributename").getValue();
if (lookup != null) {
var name = lookup[0].name;
var id = lookup[0].id;
var entityType = lookup[0].entityType;
}
//Set a lookup value
var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = recorid;
lookup[0].name = recordname;
lookup[0].entityType = entityname;
Xrm.Page.getAttribute("attributename").setValue(lookup);
Alternate method to set lookup value
Xrm.Page.getAttribute("attributename").setValue([{ id: recorid, name: recordname, entityType: entityname}]);
拿到当前记录的id
Xrm.Page.data.entity.getId();
拿到当前用户的id
Xrm.Page.context.getUserId();
改变字段的require level
Xrm.Page.data.entity.attributes.get('new_utilizationtype').setRequiredLevel("required");
Xrm.Page.data.entity.attributes.get('new_adjustmenteffectiveweek').setRequiredLevel("none");
货币字段赋值
Xrm.Page.data.entity.attributes.get("currencyfield ").setValue(value);
Xrm.Page.data.entity.attributes.get("currencyfield ").getValue(value);
lookup字段赋值
var owner = new Array();
owner[0] = new Object();
owner[0].entityType = "systemuser";
owner[0].id = Xrm.Page.context.getUserId();
Xrm.Page.data.entity.attributes.get("new_fcaapprover").setValue(owner);
日期类型字段赋值
Xrm.Page.data.entity.attributes.get("new_fcaapproverejecttime").setValue(new Date());
设置字段的保存模式
Xrm.Page.data.entity.attributes.get("new_fcaapprover").setSubmitMode("always");
设置section的显示/隐藏
var secActual = Xrm.Page.ui.tabs.get("tabAdjustmentDetails").sections.get("secActual");
secActual.setVisible(false);
常用的保存数据的方法
Xrm.Page.data.refresh(true);
Xrm.Page.data.save().then(
function () {
successHandler();
},
function (error) {
Xrm.Utility.alertDialog(error.message);
});
在IFrame里边设置父页面(CRM页面)上字段的值
parent.Xrm.Page.data.entity.attributes.get("new_tagselected").setValue("value");
Script操作数据
创建
//创建
SDK.REST.createRecord(
account,
"Account",
function (account) {
writeMessage("The account named \"" + account.Name + "\" was created with the AccountId : \"" + account.AccountId + "\".");
writeMessage("Retrieving account with the AccountId: \"" + account.AccountId + "\".");
retrieveAccount(account.AccountId)
},
errorHandler
);
this.setAttribute("disabled", "disabled");
}
查询
//查询
function retrieveAccount(AccountId) {
SDK.REST.retrieveRecord(
AccountId,
"Account",
null,null,
function (account) {
},
errorHandler
);
}
或者是:
function ParticipantAliasChange() {
var participantAlias = Xrm.Page.data.entity.attributes.get("new_participantalias").getValue();
var option = "$filter=&$select=";
var result = RetrieveMultipleRecords("", option);
}
function RetrieveMultipleRecords(type, option) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ret;
$.ajax({
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + type + "Set?" + option,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
ret = data.d.results;
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
}
});
return ret;
}
function RetrieveRecord(type, id) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ret;
$.ajax({
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + type + "Set(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
ret = data.d;
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
}
});
return ret;
}
更新
//更新
function updateAccount(AccountId) {
var account = {};
writeMessage("Changing the account Name to \"Updated Account Name\".");
account.Name = "Updated Account Name";
writeMessage("Adding Address information");
account.Address1_AddressTypeCode = { Value: 3 }; //Address 1: Address Type = Primary
account.Address1_City = "Sammamish";
account.Address1_Line1 = "123 Maple St.";
account.Address1_PostalCode = "98074";
account.Address1_StateOrProvince = "WA";
writeMessage("Setting E-Mail address");
account.EMailAddress1 = "someone@microsoft.com";
SDK.REST.updateRecord(
AccountId,
account,
"Account",
function () {
writeMessage("The account record changes were saved");
deleteAccount(AccountId);
},
errorHandler
);
}
删除
//删除
function deleteAccount(AccountId) {
if (confirm("Do you want to delete this account record?")) {
writeMessage("You chose to delete the account record.");
SDK.REST.deleteRecord(
AccountId,
"Account",
function () {
writeMessage("The account was deleted.");
enableResetButton();
},
errorHandler
);
}
else {
var li = document.createElement("li");
var span = document.createElement("span");
setElementText(span, "You chose not to delete the record. You can view the record ");
var link = document.createElement("a");
link.href = SDK.REST._getClientUrl() + "/main.aspx?etc=1&id=%7b" + AccountId + "%7d&pagetype=entityrecord";
link.target = "_blank";
setElementText(link, "here");
li.appendChild(span);
li.appendChild(link);
output.appendChild(li);
enableResetButton();
}
}
function getFirstContactToBePrimaryContact() {
SDK.REST.retrieveMultipleRecords(
"Contact",
"$select=ContactId,FullName&$top=1",
function (results) {
var firstResult = results[0];
if (firstResult != null) {
primaryContact = results[0];
}
else {
writeMessage("No Contact records are available to set as the primary contact for the account.");
}
},
errorHandler,
function () {
//OnComplete handler
}
);
}
分派
var ret = AssignRequest("new_ubiadjustment", Xrm.Page.data.entity.getId(), "team", assignee[0].TeamId, null);
if (ret == false) {
alert("Action Failed, the Team you assigned to have not enough privilege on this record.");
return;
}
function AssignRequest(entityType, entityId, assigneeType, assigneeId, assigneeName) {
var ret = true;
var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
request += "<s:Body>";
request += "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\"";
request += " xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
request += "<request i:type=\"b:AssignRequest\"";
request += " xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\"";
request += " xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
request += "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
request += "<a:KeyValuePairOfstringanyType>";
request += "<c:key>Target</c:key>";
request += "<c:value i:type=\"a:EntityReference\">";
request += "<a:Id>" + entityId + "</a:Id>";
request += "<a:LogicalName>" + entityType + "</a:LogicalName>";
request += "<a:Name i:nil=\"true\" />";
request += "</c:value>";
request += "</a:KeyValuePairOfstringanyType>";
request += "<a:KeyValuePairOfstringanyType>";
request += "<c:key>Assignee</c:key>";
request += "<c:value i:type=\"a:EntityReference\">";
request += "<a:Id>" + assigneeId + "</a:Id>";
request += "<a:LogicalName>" + assigneeType + "</a:LogicalName>";
if (assigneeName == null) {
request += "<a:Name i:nil=\"true\" />";
}
else {
request += "<a:Name>" + assigneeName + "</a:Name>";
}
request += "</c:value>";
request += "</a:KeyValuePairOfstringanyType>";
request += "</a:Parameters>";
request += "<a:RequestId i:nil=\"true\" />";
request += "<a:RequestName>Assign</a:RequestName>";
request += "</request>";
request += "</Execute>";
request += "</s:Body>";
request += "</s:Envelope>";
$.ajax({
type: "POST",
async: false,
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/Organization.svc/web",
data: request,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function (data, textStatus, XmlHttpRequest) {
ret = true;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
ret = false;
}
});
return ret;
}
Script操作表单元素
操作元素数据
货币
account.Revenue = { Value: "2000000.00" }; //赋值
选项集
account.PreferredContactMethodCode = { Value: 2 };
文本
account.Address1_City = "Sammamish";
查找字段
account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: "contact", Name: primaryContact.FullName } [赋值];
改变只读字段状态编辑字段进行调试
contentIFrame.Xrm.Page.getControl("Key").setDisabled(false);
获取初始值
Xrm.Page.data.entity.attributes.get("new_flow_type").getInitialValue();
获取窗体是否未保存
Xrm.Page.data.entity.getIsDirty();
设置表单元素
设置Tab
Xrm.Page.ui.tabs.get("Key").setVisible(false);//隐藏
Xrm.Page.ui.tabs.get("Key").setVisible(true);//显示
Disable页面所有字段
function DoesControlHaveAttribute(control) {
var controlType = control.getControlType();
return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}
function DisableFormFields() {
Xrm.Page.ui.controls.forEach(function (control, index) {
if (DoesControlHaveAttribute(control)) {
control.setDisabled(true);
}
});
}
设置Tab中的节
Xrm.Page.ui.tabs.get("tab_1").sections.get("tab_2_section_6").setVisible(false);//隐藏
Xrm.Page.ui.tabs.get("tab_1").sections.get("tab_2_section_6").setVisible(true);//显示
设置字段只读/可编辑
Xrm.Page.getControl("new_systemuserid").setDisabled(true);
Xrm.Page.getControl("new_systemuserid").setDisabled(false);
设置字段可见/隐藏
Xrm.Page.getControl("new_systemuserid").setVisible(true);
Xrm.Page.getControl("new_systemuserid").setVisible(false);
设置字段赋值后自动提交
Xrm.Page.getAttribute("new_systemuserid").setSubmitMode("always");
传递dialog的值给后边的页面
window.opener.window.parent.Xrm.Page.getAttribute("ws_name").setValue('fsdfs');
其他常用方法
拿到用户所属的team
function GetTeamsOfUser(ownerId) {
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>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>team</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>name</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkCriteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
"<q1:Values>" +
//code to get the owner
"<q1:Value xsi:type=\"xsd:string\">" + ownerId + "</q1:Value>" +
"</q1:Values>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:LinkCriteria>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");
var teamsArray = new Array();
for (var i = 0; i < entityNodes.length; i++) {
var teamItem = new Object();
var entityNode = entityNodes[i];
var teamidNode = entityNode.selectSingleNode("q1:teamid");
var teamNode = entityNode.selectSingleNode("q1:name");
var teamid = (teamidNode == null) ? null : teamidNode.text;
var team = (teamNode == null) ? null : teamNode.text;
teamItem.teamID = teamid;
teamItem.teamName = team;
teamsArray[i] = teamItem;
}
return teamsArray;
}
查询N:N记录
Type是这个N:N 关系的logicalname
var type = "new_campaign_contact";
var option = "$select=new_campaign_contactId&$filter=campaignid eq guid'" + Xrm.Page.data.entity.getId()+"+'";
var result = RetrieveMultipleRecords(type, option);
function RetrieveMultipleRecords(type, option) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ret;
$.ajax({
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + type + "Set?" + option,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
ret = data.d.results;
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
}
});
return ret;
}
function RetrieveNNRelationship(FromEntity, ToEntity, RelationShip, reasonId) {
var fetchxml =
"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' >" +
"<entity name='" + FromEntity + "'>" +
"<attribute name='" + FromEntity + "id' />" +
"<attribute name='domainname'/>" +
"<attribute name='internalemailaddress'/>" +
"<attribute name='firstname'/>" +
"<attribute name='lastname'/>" +
"<link-entity name='" + RelationShip + "' from='" + FromEntity + "id' to='" + FromEntity + "id'>" +
"<link-entity name='" + ToEntity + "' from='" + ToEntity + "id' to='" + ToEntity + "id'>" +
"<filter type='and'>" +
"<condition attribute='" + ToEntity + "id' operator='eq' value='" + reasonId + "' />" +
"</filter>" +
"</link-entity>" +
"</link-entity>" +
"</entity>" +
"</fetch>";
var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
request += "<s:Body>";
request += '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">' + '<request i:type="b:RetrieveMultipleRequest" ' + ' xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" ' + ' xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' + '<b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' + '<b:KeyValuePairOfstringanyType>' +'<c:key>Query</c:key>' + '<c:value i:type="b:FetchExpression">' + '<b:Query>';
request += CrmEncodeDecode.CrmXmlEncode(fetchxml);
request += '</b:Query>' + '</c:value>' + '</b:KeyValuePairOfstringanyType>' + '</b:Parameters>' + '<b:RequestId i:nil="true"/>' + '<b:RequestName>RetrieveMultiple</b:RequestName>' + '</request>' + '</Execute>';
request += '</s:Body></s:Envelope>';
var serverURL = Xrm.Page.context.getServerUrl();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", serverURL + "/XRMServices/2011/Organization.svc/web", false);
xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction","http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
try { xmlhttp.responseType = 'msxml-document'; } catch (e) { };
xmlhttp.send(request);
xmlhttp.responseXML.setProperty("SelectionNamespaces", "xmlns:a=\'http://schemas.microsoft.com/xrm/2011/Contracts\'");
var sFetchResult = xmlhttp.responseXML.selectSingleNode("//a:Entities").xml;
var resultDoc = new ActiveXObject("Microsoft.XMLDOM");
resultDoc.async = false;
resultDoc.loadXML(sFetchResult);
//parse result xml into array of jsDynamicEntity objects
var results = new Array(resultDoc.firstChild.childNodes.length);
for (var i = 0; i < resultDoc.firstChild.childNodes.length; i++) {
var userEntity = resultDoc.firstChild.childNodes[i];
var userItem = new Object();
var userId = "";
var userName = "";
for (var j = 0; j < userEntity.childNodes.length; j++) {
var key = userEntity.childNodes[j];
if (key.baseName == "Attributes") {
for (var k = 0; k < key.childNodes.length; k++) {
var attr = key.childNodes[k];
if (attr.childNodes[0].nodeTypedValue == FromEntity + "id") {
userId = attr.childNodes[1].nodeTypedValue;
}
if (attr.childNodes[0].nodeTypedValue == "firstname")
var firstname = attr.childNodes[1].nodeTypedValue;
if (attr.childNodes[0].nodeTypedValue == "lastname")
var lastname = attr.childNodes[1].nodeTypedValue;
userName = firstname + " " + lastname;
}
}
}
userItem.id = userId;
userItem.name = userName;
results[i] = userItem;
}
return results;
}
跳转页面
function redirectaccount(accountid) {
Xrm.Page.ui.close();//关闭当前页面
Xrm.Utility.openEntityForm("account", accountid);//打开其他记录页面
}
Dynamics CRM 常用 JS 方法集合的更多相关文章
- Dynamics CRM 常用 C# 方法集合
Plugin(C#) 分派 AssignRequest assign = new AssignRequest(); assign.Assignee = prEntity["ownerid&q ...
- Microsoft Dynamics CRM 常用JS语法(已转成vs2017语法提示)
背景 最近接触到Microsoft Dynamics CRM的开发.前端js是必不可少的部分,奈何没有一个语法提示,点不出来后续的语句. 在vscode上面搜索插件的时候发现,有一个大神写的插件htt ...
- 常用js方法集合
var func={ //对象转jsonstring getJsonStr: function(jsonObj) { var temp = []; for (var key in jsonObj) { ...
- 常用js方法
function dateGetter(name, size, offset, trim) { offset = offset || 0; return function (date) { var v ...
- 常用js方法整理common.js
项目中常用js方法整理成了common.js var h = {}; h.get = function (url, data, ok, error) { $.ajax({ url: url, data ...
- 项目中常用js方法整理common.js
抽空把项目中常用js方法整理成了common.js,都是网上搜集而来的,大家一起分享吧. var h = {}; h.get = function (url, data, ok, error) { $ ...
- 常用js方法封装
常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...
- Dynamics CRM 常用的JS
常用JS(一) Xrm.Page.context.getUserId(): //获取当前用户id Xrm.Page.context.getUserName(): //获取当前用 ...
- Microsoft Dynamics CRM4.0 和 Microsoft Dynamics CRM 2011 JScript 方法对比
CRM 2011 如果需要再IE里面调试,可以按F12在前面加上contentIFrame,比如 contentIFrame.document.getElementById("字段" ...
随机推荐
- Python:常见错误集锦(持续更新ing)
初学Python,很容易与各种错误不断的遭遇.通过集锦,可以快速的找到错误的原因和解决方法. 1.IndentationError:expected an indented block 说明此处需要缩 ...
- centos7启动时出现“无法应用原保存的显示器配置”
设置了分辨率后,登录提示“出现无法应用原保存的显示器配置”. 解决办法: 打开终端,输入 rm ~/.config/monitors.xml 然后重新登录, 问题解决.
- linux添加JAVA环境变量
root用户: 1.修改文件vim /etc/profile 添加以下信息: export JAVA_HOME=/home/jdk1..0_79 (这里需要添加自己的JDK安装目录) export C ...
- ajax初学
//参数说明url:请求文件地址//fnSucc:请求成功执行的函数,请求成功的条件为readyState状态码为4:且status状态码为200,status状态为浏览器请求返回的状态码//在fnS ...
- px em rem
px 在Web页面初期制作中,我们都是使用“px”来设置我们的文本,因为他比较稳定和精确.但是这种方法存在一个问题,当用户在浏览器中浏览我们制作的Web页面时,他改变了浏览器的字体大小,这时会使用我们 ...
- 转载:struts2和spring的结合原理(精品)
转载网址:http://blog.sina.com.cn/s/blog_683278bc0101236z.html Ioc将所有的对象之间的关系转移到了xml配置文件中来. 在TopLogic中声明存 ...
- CSAPP--虚拟存储器
虚拟存储器 虚拟存储器(VM)是对主存的一种抽象概念.是硬件一场,硬件地址翻译,贮存,磁盘文件和内核软件的完美交互.他为每个进程提供了一个大的,一致的和私有的地址空间. 它将贮存堪称一个存储在磁盘上的 ...
- UCOS 信号量
uCOS-II信号量OSSemCreate(0)和OSSemCreate(1)详解 (2014-04-22 18:04:18) 转载▼ 标签: it 分类: 操作系统 在ucos-II中,为了实现任务 ...
- Scala学习笔记--文件IO
补充: http://blog.csdn.net/lyrebing/article/details/20369445 http://developer.51cto.com/art/200907/134 ...
- python的pyc和pyo文件
python并非完全是解释性语言,它是有编译的,先把源码py文件编译成pyc或者pyo,然后由python的虚拟机执行,相对于py文件来说,编译成pyc和pyo本质上和py没有太大区别,只是对于这个模 ...