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 方法集合的更多相关文章

  1. Dynamics CRM 常用 C# 方法集合

    Plugin(C#) 分派 AssignRequest assign = new AssignRequest(); assign.Assignee = prEntity["ownerid&q ...

  2. Microsoft Dynamics CRM 常用JS语法(已转成vs2017语法提示)

    背景 最近接触到Microsoft Dynamics CRM的开发.前端js是必不可少的部分,奈何没有一个语法提示,点不出来后续的语句. 在vscode上面搜索插件的时候发现,有一个大神写的插件htt ...

  3. 常用js方法集合

    var func={ //对象转jsonstring getJsonStr: function(jsonObj) { var temp = []; for (var key in jsonObj) { ...

  4. 常用js方法

    function dateGetter(name, size, offset, trim) { offset = offset || 0; return function (date) { var v ...

  5. 常用js方法整理common.js

    项目中常用js方法整理成了common.js var h = {}; h.get = function (url, data, ok, error) { $.ajax({ url: url, data ...

  6. 项目中常用js方法整理common.js

    抽空把项目中常用js方法整理成了common.js,都是网上搜集而来的,大家一起分享吧. var h = {}; h.get = function (url, data, ok, error) { $ ...

  7. 常用js方法封装

    常用js方法封装 var myJs = { /* * 格式化日期 * @param dt 日期对象 * @returns {string} 返回值是格式化的字符串日期 */ getDates: fun ...

  8. Dynamics CRM 常用的JS

    常用JS(一) Xrm.Page.context.getUserId():       //获取当前用户id Xrm.Page.context.getUserName():       //获取当前用 ...

  9. Microsoft Dynamics CRM4.0 和 Microsoft Dynamics CRM 2011 JScript 方法对比

    CRM 2011 如果需要再IE里面调试,可以按F12在前面加上contentIFrame,比如 contentIFrame.document.getElementById("字段" ...

随机推荐

  1. USB 管道 && 端点

    管道是对主机和usb设备间通信流的抽象.      管道和usb设备中的端点一一对应,一个usb设备含有多少个端点,其和主机进行通信时就可以使用多少条管道,且端点的类型决定了管道中数据的传输类型.  ...

  2. 常用分组函数count-avg-sum-max-min

    分组函数也称多行函数,用于对一组数据进行运算,针对一组数据(取自于多行记录的相同字段)只返回一个结果,例如计算公司全体员工的工资总和.最高工资.最低工资.各部门的员工平均工资(按部门分组)等.由于分组 ...

  3. Linux的VI/VIM

    参考自:http://www.cnblogs.com/itech/archive/2009/04/17/1438439.html 作者:iTech 出处:http://itech.cnblogs.co ...

  4. scala学习笔记-集合

    变长数组:数组缓冲 Scala中对于那种长度会变的数组的数据结构为ArrayBuffer. import scala.collection.mutable.ArrayBuffer; // 一个空的数组 ...

  5. The Suspects

    算法:并查集 严重急性呼吸系统综合症( SARS), 一种原因不明的非典型性肺炎,从2003年3月中旬开始被认为是全球威胁.为了减少传播给别人的机会, 最好的策略是隔离可能的患者. 在Not-Spre ...

  6. uva 11536 - Smallest Sub-Array

    题目大意:按照题目中的要求构造出一个序列,找出最短的子序列,包含1~k. 解题思路:先根据题目的方法构造出序列,然后用Towpointer的方法,用v[i]来记录当前[l, r]中有几个i:当r移动时 ...

  7. mongodb安装指南

    mongodb安装 1.解压mongodb-win32-i386-1.8.1.zip ,创建路径C:\Program Files\mongodb ,将解压后的Bin文件Copy to 此文件夹下 2. ...

  8. js获取鼠标选中的文字

    1.获取选中的文字: document.selection.createRange().text; IE9以下使用 window.getSelection().toString(); 其他浏览器使用 ...

  9. HTML&CSS基础学习笔记1.23-表单的文本域和下拉列表

    文本域 <textarea>标签定义多行的文本输入控件. 平时在网页上的一些需要输入比较多的内容的输入框,比如回复帖子,回答问题等,都可以用<textarea>标签. < ...

  10. Spark问题记录

    Spark 多线程时的序列化问题  临时记录 Exception in thread "Thread-28" org.apache.spark.SparkException: Ta ...