[Dynamics CRM 2016] 基礎操作


來源:

https://blog.csdn.net/jxian2009/article/details/22179447

http://www.cnblogs.com/allenhua/archive/2012/12/25/2832473.html

 

 

MSCRM 2011 操作大全

CRM字段類型:
貨幣:new Money(Decimal){SQL更新Money類型字段,需要同時更新_base字段,存在匯率差的時候值不同}
查找:new EntityReference(objecttypename,Guid)
下拉:new OptionSet(Int)
選項集:false/true
時間:DateTime
整數:Integer
十進制數:Decimal
浮點數:Double
單行/多行文本:String
CRM系統:
存儲列表值:StringMap
存儲附件:annotation


CRM,8個基本數據操作:
Associate 創建多對多關系
Create 創建數據
Delete 刪除數據
Disassociate 刪除多對多關系
Execute 執行請求  
Retrieve 查詢一個記錄
RetrieveMultiple 查詢多個記錄
Update 更新數據  


1.Xrm.Page.context
用戶ID:getUserId()
用戶角色:getUserRoles()
用戶語言:getUserLcid()
組織名稱:getOrgUniqueName()
組織語言:getOrgLcid()
路徑參數:getQueryStringParameters()
服務器路徑:getServerUrl()/getClientUrl()
前追加組織名稱:prependOrgName("/WebResource/**")效果:crmtest/WebResource/**
當前主題:getCurrentTheme()
OutLook:isOutlookClient()/isOutlookOnline()


2.Xrm.Page.data.entity
所有頁面元素:attributes【forEach(),get(),getLength()】
單個元素:attributes.get("")【同Xrm.Page.getAttribute()】
實體名稱:getEntityName()
實體ID:getId()
是否修改:getIsDirty()
保存事件:save()
添加保存時事件:addOnSave()
移出保存時事件:removeOnSave()

3.Xrm.Page.getAttribute("")
取值:getValue()
賦值:setValue()
是否改動:getIsDirty()
表單載入時的值:getInitialValue()[Boolean, optionset]
提交類型:getSubmitMode(),setSubmitMode()//always,never,ditry
必填等級:getRequiredLevel(),setRequiredLevel()//required、none
用戶操作等級:getUserPrivilege()//canCreate()、canRead()、canUpdate()
事件:addOnChange(),removeOnChange(),fireOnChange()[強制執行]
其他:getAttributeType(),getFormat(),getMax(),getMaxLength(),getMin(),getName(),getParent(),getPrecision()
optionset:getOption(),getOptions(),getSelectedOption(),getText()

4.Xrm.Page.getControl("")
屬性:getAttribute()【同Xrm.Page.getAttribute()】
禁用/啟用:setDisabled(true),setDisabled(false),getDisabled()
顯示/隱藏:setVisible(true),setVisible(false),getVisible()
描述:setLabel(),getLabel()
聚焦選中:setFocus
刷新:refresh()//僅限SubGrid
其他:addCustomView(),addOption(),removeOption(value),clearOptions(),getControlType(),getData(),setData(),getDefaultView(),setDefaultView(),getName(),getParent(),getSrc(),setSrc(),getInitialUrl(),getObject()


5.Xrm.Page.ui
頁面所有控件:controls【forEach(),get(),getLength()】
單個控件:controls.get("")【同Xrm.Page.getControl()】


頁面Tab:tabs【forEach(),get(),getLength()】
單個Tab:tabs.get()【sections,getDisplayState(),getLabel(),getName(),getParent(),getVisible(),setDisplayState(),setFocus(),setLabel(),setVisible()】


Tab-Sections:tabs.get(0).sections【forEach(),get(),getLength()】
單個Section:tabs.get(0).sections.get(0)【getLabel(),getName(),getParent(),getVisible(),setLabel(),setVisible(),controls】


頁面導航:navigation.items【forEach(),get(),getLength()】
單個導航:navigation.items.get()【getId(),getLabel(),getVisible(),setFocus(),setLabel(),setVisible()】


窗體:formSelector.items【forEach(),get(),getLenght()】
單個窗體:formSelector.items.get()【getId(),getLabel(),navigate()-窗體跳躍】


6.窗體狀態
var FORM_TYPE_CREATE = 1;
var FORM_TYPE_UPDATE = 2;
var FORM_TYPE_READ_ONLY = 3;
var FORM_TYPE_DISABLED = 4;
var FORM_TYPE_QUICK_CREATE = 5;
var FORM_TYPE_BULK_EDIT = 6;
var formType = Xrm.Page.ui.getFormType();


刷新當前頁面:
window.location.href = window.location.href;
window.location.reload();


禁用頁面所有控件:
Xrm.Page.ui.controls.forEach(function (control, index) {
control.setDisabled(true);
});


防止保存事件(需要執行上下文):
function My_PreventSaveFunction(eContext) {
 eContext.getEventArgs().preventDefault();
}


給Lookup取值賦值:
id:obj.getValue()[0].id;
name:obj.getValue()[0].name;

var objList = new Array();
var obj = new Object();
obj.id = accountObj[0].TerritoryId.Id;
obj.name = accountObj[0].TerritoryId.Name;
obj.typename = accountObj[0].TerritoryId.LogicalName;
objList[0] = obj;
Xrm.Page.getAttribute("yto_territory").setValue(accountObj[0].TerritoryId.Id == null ? null : objList);
Xrm.Page.getAttribute("yto_territory").setSubmitMode("always");
Xrm.Page.data.entity.save();

給OptionSet按條件顯示列:
Xrm.Page.getControl("new_counter_type").clearOptions();
var options = Xrm.Page.getAttribute("new_counter_type").getOptions();
for (var i = 0; i < options.length; i++) {
if (options[i].value != 190 && options[i].value != 200 && options[i].value!="null" ) {
Xrm.Page.getControl("new_counter_type").addOption(options[i], i+1);
}
}
Xrm.Page.getControl("new_counter_type").addOption(Xrm.Page.getAttribute("new_counter_type").getOption(190),1);


JS,給日期類型控件賦值:
var fullYear = Xrm.Page.getAttribute("yto_confirmdate").getValue().getFullYear();
var month = Xrm.Page.getAttribute("yto_confirmdate").getValue().getMonth() + 1;
var date = Xrm.Page.getAttribute("yto_confirmdate").getValue().getDate();
Xrm.Page.getAttribute("yto_confirmdate").setValue(new Date(fullYear, month, date))//廠方確認交貨日期+1月
Xrm.Page.data.entity.save();


7.給Lookup添加過濾:
        var fetch = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true"><entity name="new_expensesdetail"><attribute name="new_expensesdetailid"/><attribute name="new_name"/><attribute name="createdon"/><order attribute="new_name" descending="false"/><filter type="and"><condition attribute="statecode" operator="eq" value="0"/></filter><link-entity name="new_buget" from="new_expenseitem" to="new_expensesdetailid" alias="aa"><filter type="and"><condition attribute="new_bugetunit" operator="eq" uitype="businessunit" value="' + Xrm.Page.getAttribute("new_businessunit").getValue()[0].id + '"/><condition attribute="new_bedgetsheet" operator="eq" uitype="new_budgetcycle" value="' + Xrm.Page.getAttribute("new_feeperiod").getValue()[0].id + '"/></filter></link-entity></entity></fetch>';
        var view = '<grid name="resultset" object="10069" jump="new_name" select="1" icon="1" preview="1"><row name="result" id="new_expensesdetailid"><cell name="new_name" width="300" /><cell name="createdon" width="125" /></row></grid>';
        Xrm.Page.getControl("new_detailitem").addCustomView("{B9C6A1F4-0A03-424D-B843-E4D9281F8DEB}", "new_expensesdetail", "根據部門和費用期間篩選", fetch, view, true);
modifiedLookupParameter("new_detailitem", "DisableViewPicker", "1");
A.取fetchxml和viewxml:
高級查找-編輯列-F12-腳本dlg_editview.aspx
frameRender.FetchXml.value
frameRender.LayoutXml.value
B.addCustomView("可用系統視圖GUID,以便覆蓋","","","","",是否默認視圖)


8.用Ribbon Editor給自定義按鈕添加JS事件:Library($webresource:web資源的名稱)
9.JS引用了REST等通用JS的方法,需在該實體的窗體庫中引用通用JS。
10.Plugin調試步驟:Plugin Registration Tool => Profile => 保存ErrorDetail.txt => Stop Profile => Debug,加載ErrorDetail.txt和DLL => VS附加PlugRegistration.exe到進程 =>Debug Start
11.Plugin拋異常到頁面:throw new InvalidPluginExecutionException("");
12.Plugin取值:
int statuscode = (preImageEntity.Attributes["statuscode"] as OptionSetValue).Value;
13.Plugin刪除了類文件,還需要去RegisterFile.crmregister刪除對應的引用,否則會出現部署失敗
14.高級查找-編輯列-F12未出現開發人員工具:IE-Internet選項-安全-Internet-自定義級別-允許網站打開沒有地址或狀態欄的窗口-禁用
15.是否出現“添加已存在**明細”按鈕方法:明細表中主表字段的必填等級=業務必須,則不出現添加已存在按鈕,否則出現。
16.刪除一個表數據,在Pre-Delete中,已經把與之關聯的數據中包含它的字段都NULL了。查詢與之關聯的數據,不能再通過該字段。
17.貨幣類型后台賦值:new Money(decimal.Parse())
18.菜單關聯視圖:<SubArea Id="yto_yto_applytogoods_dqr" Title="待確認的要貨申請" Icon="/_imgs/ico_16_customEntity.gif" Url="_root/homepage.aspx?etn=yto_applytogoods&amp;viewid=%7b98B36DFB-4BA3-E211-8F62-00155D04D707%7d"></SubArea>
【函數】19.動態載入JS(CRM函數):loadScriptAdv("腳本URL","任意ID",false);
loadScriptAdv(Xrm.Page.context.prependOrgName("/WebResources/fw_rest"), "55EE635C-91BD-443F-A3E6-56ACEG4E574G", false);
【函數】20.獲取Homepage選擇的項(CRM函數):getSelected("crmGrid")
【函數】打開模式窗口openStdDlg()
windos.open("http://172.16.4.215/yto/main.aspx?etc=1&id=%7ba7402069-e4db-e211-9396-90b11c1d4ddf%7d&pagetype=entityrecord","_blank");
21.插件異步:異步plugin需要異步服務執行,這個啟動時間會比較慢。POST后才會去啟動這個操作。另外,異步作業有個特點,就是可還原操作。出錯了,改完數據或修正plugin,可以將操作繼續執行。
22.VS新建解決方案,選不了組織,因為本機不能識別CRM電腦名,要添加HOSTS映射:172.16.4.217 crmtest
23.JS給日期控件賦值:Xrm.Page.getAttribute("yto_date").setValue(new Date()),但是JS取客戶機時間,建議在JS賦值的基礎上再用PreValidate插件
24.JS刷新CRM視圖:Mscrm.Utilities.refreshCurrentGrid(entityTypeCode);
25.注意。報表做時間類型的比對時,在第一行把時間類型參數dbo.fn_LocalTimeToUTC()轉成UTC時間。dbo.fn_UTCToLocalTime()轉成本地時間
set @startDate=isnull(@startDate,'1900-01-01')
set @startDate=dbo.fn_LocalTimeToUTC(@startDate)
set @endDate=dbo.fn_LocalTimeToUTC(DATEADD(DD,1,@endDate))
26.多條記錄拼接為一個字符串: 
SELECT @re=@re+','+yto_name FROM yto_order
select @new_businessunit= stuff((select ';'+convert(varchar(50),businessunitid) from businessunit for xml path('')),1,1,'') 
27.導入解決方案之后,需要去檢查關於擴展功能的插件有沒有出現重復項,刪除較早的,不然會出現審批之后,按鈕不會改變的問題。
28.不要使用任何系統自帶的字段,如狀態描述、創建日期來當作單據的字段使用!
29.域用戶需要在CRM部署管理器中加入CRM部署管理員,才能進行開發和部署操作。
30.貨幣類型的字段賦值:=new Money(decimail)     !!!,切記。
31.VS鏈接項目發生安全性的問題,因為CRM服務器和本機的時間相隔超過5分鍾。
32.Pre_Create中,不能用entity.Id來做引用,因為目前該數據尚不存在。
00000000-0000-0000-0000-000000000000
34.VS解決方案不顯示CRM視圖:修改“解決方案.sln”文件,添加節點
GlobalSection(CRMSolutionProperties) = preSolution
SolutionIsBoundToCRM = True
EndGlobalSection
35.轉REST獲取的日期類型(從“/Date***”到“Fri Nov 1 00:00:00 UTC+0800 2013”)
function dateReviver(value) {
    var a;
    if (typeof value === 'string') {
        a = /Date\(([-+]?\d+)\)/.exec(value);
        if (a) {
            return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
        }
    }
    return value;
};
36.REST查詢需要的日期類型轉換:var myDate = (new Date()).format("yyyy-MM-ddThh:mm:ss");
37.值為NULL的列查詢后不包含在實體中:!Contains("")
38.實體創建的時候可以給ownerid賦值,但更新的時候給ownerid賦值不會更新。
39.CRM組織服務更新日期字段時,DateTime.Now和DateTime.UtcNow插入到數據庫的值是一樣的。
40.
【誤區】
日期賦值:
entity["date1"]=entity["date2"]是對的(顯示:2013.1.2;date1:2013.1.1 16:00:00 date2:2013.1.1 16:00:00);
entity["date1"]=DateTime.Parse(entity["date2"].ToString())是錯的(顯示:2013.1.2 date1:2013.1.1 8:00:00已錯 date2:2013.1.1 16:00:00)
entity["date1"] = DateTime.Now、entity["date1"] = DateTime.UtcNow,結果是一樣的!(2013.1.1 16:00:00)
取值:
(DB,Retrieve,Image,Entity上取的都是-8H的,只有頁面顯示已經+8H)所以JS中和CS中的比較一定要注意。
41.通過數據庫還原新組織后,由於頂級組織改變,所有業務部門的guid會改變。
42.CRM數據庫新建視圖后,給新用戶權限,需‘授予’查詢的實體和關聯實體的視圖的‘選擇’權限就行了。
43.刪除或者更新數據的時候,用最高權限的用戶初始化的組織服務。
44.context.SharedVariables插件間的參數傳遞,注意context不同的時候,獲取不到,所以最好用頂級context。
45.關於實體字段“貨幣”的賦值:service中create和update實體的時候,只有帶上貨幣類型字段,“貨幣”會自動賦值。




1.發現服務-http://crmpc/XRMServices/2011/Discovery.svc  (用來發現域下面有哪些組織)
2.SOAP組織服務-http://crmpc/yto/XRMServices/2011/Organization.svc   (C#試用的標准的數據服務)
3.OData組織服務-http://crmpc/yto/XRMServices/2011/OrganizationData.svc   (平時使用的rest腳本數據服務)


1.[SetStateDynamicEntity]
獲取實體:
EntityReference entity = context.InputParameters.Contains("EntityMoniker") ? context.InputParameters["EntityMoniker"] as EntityReference : null;
獲取狀態:
OptionSetValue state = context.InputParameters["State"] as OptionSetValue;
OptionSetValue status = context.InputParameters["Status"] as OptionSetValue;
修改狀態:
SetStateRequest setState = new SetStateRequest();
setState.EntityMoniker = new EntityReference("task", task1.Id);
setState.State = new OptionSetValue(1);
setState.Status = new OptionSetValue(5);
testService.Execute(setState);


2.
JS查詢(查詢條件是中文需要轉符encodeURI(),可關聯查詢expand是關系名稱)
var obj = rest.get("new_shopSet(guid'" + new_original_shopid[0].id + "')?$select=new_ERP,new_account_shop,new_account_new_shop2/new_company_type&$expand=new_account_new_shop2");


var account = Xrm.Page.getAttribute("yto_account");
var rest=new fwREST();
var accountObj = rest.get("AccountSet?$select=Address1_Name,TerritoryId&$filter=AccountId eq guid'" + account.getValue()[0].id + "'");
if (accountObj.error != undefined) {
alert("yto_applytogoods|JS|onchangeAccount|獲取客戶地址區域失敗:" + accountObj.error.message.value);
return;
} else {
if (accountObj.length > 0) {
Xrm.Page.getAttribute("yto_dealeraddress").setValue(accountObj[0].Address1_Name);
}
}
主鍵:obj[0].名稱
Lookup:obj[0].Id;obj[0].LogicalName;obj[0].Name; 判斷:obj[0].Id!=null
Optionset:obj[0].名稱.Value;
JS創建業務部門
var rest = new fwREST();
var newBusinessUnit = new Object();
newBusinessUnit.Name = "testBusinessUnit";
newBusinessUnit.ParentBusinessUnitId = new Object();
newBusinessUnit.ParentBusinessUnitId.LogicalName = "businessunit";
newBusinessUnit.ParentBusinessUnitId.Id = "{F3A5B2E9-C150-E211-AD82-50465D6B1E0D}";//根部門GPX
var createBusinessJson=JSON.stringify(newBusinessUnit);
var createBusinessResult = rest.create("BusinessUnit", createBusinessJson);
if (createBusinessResult.error != undefined) {
alert("Account|JS|createSystemAccount|創建失敗:" + createBusinessResult.error.message.value);
return;
} else {
var newBusinessUnitId = createBusinessResult.BusinessUnitId;
alert(newBusinessUnitId);
}
JS更新客戶
var rest = new fwREST();
var newAccount = new Object();
newAccount.new_account_status = new Object();
newAccount.new_account_status.Value = 100000000;
var content=new Object();
content.Id="";
content.LogicalName="";
//content.Name="";
newAccount.content=content;
newAccount.new_isconfirm = true;//單選類型
rest.update("Account", id, JSON.stringify(newAccount), function (res) {
if (res.error != undefined) {
alert("Account|JS|createSystemAccount|更新失敗:" + res.error.message.value);
return;
}
});


2.服務器復合查詢
//根據客戶ID獲取客戶類型
private int GetAccounttypeById(Guid accountId, IOrganizationService service)
{
int yto_accounttype = 0;
string fetchxml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='yto_accounttype' />
<filter type='and'>
<condition attribute='statecode' operator='eq' value='0' />
<condition attribute='accountid' operator='eq' value='" + accountId + @"' />
</filter>
</entity>
</fetch>";
EntityCollection entityCollection = service.RetrieveMultiple(new FetchExpression(fetchxml));
foreach (var entity in entityCollection.Entities)
{
if (entity.Contains("yto_accounttype"))
{
yto_accounttype = (entity["yto_accounttype"] as OptionSetValue).Value;
}
}
return yto_accounttype;
}
fetchXML查詢的分組和統計
<fetch distinct='false' mapping='logical' aggregate='true'>
<attribute name='new_amount' alias='new_amount_sum' aggregate='sum' />
<attribute name='new_bugetid'  groupby='true' alias='new_bugetid_all' />
取值
 (((AliasedValue)item["new_bugetid_all"]).Value as EntityReference)


3.Lookup記錄選擇窗口完全自定義方式
var lookupViewArgs = {
    items: null,
    customViews: [{
        id: "{F86239AE-C483-E211-B9C3-00155D332305}",           //自定義視圖ID(隨意取)
        recordType: 2,                          //實體類型
        name: "TEST",                           //自定義視圖名稱
        fetchXml: '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true"><entity name="contact"><attribute name="fullname"/><attribute name="telephone1"/><attribute name="contactid"/><order attribute="fullname" descending="false"/><link-entity name="new_test" from="new_contact" to="contactid" alias="ak"><link-entity name="account" from="accountid" to="new_account" alias="al"><filter type="and"><condition attribute="accountid" operator="eq" uiname="Fabrikam, Inc. &amp;#40;&amp;#31034;&amp;#20363;&amp;#41;" uitype="account" value="{F86239AE-C483-E211-B9C3-00155D332305}"/></filter></link-entity></link-entity></entity></fetch>',
        layoutXml: '<grid name="resultset" object="2" jump="lastname" select="1" icon="1" preview="1"><row name="result" id="contactid"><cell name="fullname" width="300" /><cell name="telephone1" width="125" /></row></grid>',
        Type: 0
    }],
    availableViews: null
};
var url = "http://crm2011s/Demo/_controls/lookup/lookupinfo.aspx?AllowFilterOff=1&DefaultType=2&DefaultViewId=%7bF86239AE-C483-E211-B9C3-00155D332305%7d&DisableQuickFind=0&DisableViewPicker=0&LookupStyle=single&ShowNewButton=1&ShowPropButton=1&browse=false&objecttypes=2";
openStdDlg(url, lookupViewArgs, 800, 500);


4.連接CRM服務器:
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
CrmConnection connection = CrmConnection.Parse("Url=http://192.168.2.174/Liby;Username=administrator;Password=Pa$$w0rd;Domain=LIBYCRM;");
CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection);


5.手動執行審批流下一步(fw_action和fw_workflow_directionid[可以不用更新])
Entity fw_wf_user_task = new Entity("fw_wf_user_task");
fw_wf_user_task.Id = entityCollection.Entities[0].Id;
fw_wf_user_task["fw_action"] = new OptionSetValue(300000001);
//fw_wf_user_task["fw_workflow_directionid"] = new EntityReference("fw_workflow_directing", new Guid("9E9E5C2C-659A-E211-8F62-00155D04D707"));
CrmUtil.OrgServiceContext.Update(fw_wf_user_task);
手動執行審批流JS:
var usertask = new Object();
usertask.fw_action = new Object();
usertask.fw_action.Value = 300000001;                               
var direction = new Object();
direction.Id = "9E9E5C2C-659A-E211-8F62-00155D04D707";
direction.LogicalName = "fw_workflow_directing";
usertask.fw_workflow_directionid = direction;
rest.update("fw_wf_user_task", tasks[0].fw_wf_user_taskId, JSON.stringify(usertask), function (res) {
if (res.error != undefined) {
msg += "單據[" + objs[0].yto_name + "]審批失敗:" + res.error.message.value + "\n";
} else {
msg += "單據[" + objs[0].yto_name + "]審批成功" + "/n";
}
});


6.添加了審批流的實體,在狀態變更的時候獲取的上下文登陸人是system,根據頂級上下文獲取當前真實登陸人:
/// <summary>
/// 獲取最頂級插件上下文對象
/// </summary>
/// <param name="currentContext">當前插件上下文對象</param>
/// <returns>返回最頂級插件上下文對象</returns>
public IPluginExecutionContext GetTopContext(IPluginExecutionContext currentContext)
{
IPluginExecutionContext topContext = currentContext;
for (int i = 0; i <= currentContext.Depth; i++)
{
if (topContext.ParentContext!=null)
{
topContext = topContext.ParentContext;

}
return topContext;
}


8.插件注冊管道
驗證前:  數據補充和驗證
操作前:  核心操作前對其他數據進行變更、創建、刪除(失敗可回滾)
操作后:  驗證數據執行情況,執行核心操作后的后繼工作


9.JS返回訪問平台
navigator.platform
navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)


10.JS返回日期間隔
 function dateDiff(interval, date1, date2)
    {
        var objInterval = {'D' : 1000 * 60 * 60 * 24, 'H' : 1000 * 60 * 60, 'M' : 1000 * 60, 'S' : 1000, 'T' : 1};
        interval = interval.toUpperCase();
        var dt1 = Date.parse(date1.replace(/-/g, '/'));
        var dt2 = Date.parse(date2.replace(/-/g, '/'));
        try
        {
            return Math.round((dt2 - dt1) / eval('(objInterval.' + interval + ')'));
        }
        catch (e)
        {
            return e.message;
        }
    } 
說明:interval 取值: d (day), m(minutes), s(second), t(毫秒),不分區大小寫
日期格式: yyyy (/-) (m)m (/-) (d)d


11.超過6個subgrid不會自動顯示數據(onload,參數100)
//刷新MS CRM表單中未自動加載的SubGrid
var refreshSubGridId;
function loadSubGrids(milliSeconds) {
    if (!milliSeconds) milliSeconds = 1000;
    refreshSubGridId = setInterval(refreshSubGrids, milliSeconds);
}
function refreshSubGrids() {
    var blnSuccess = false;
    try {
        var subgrids = Xrm.Page.ui.controls.get(function (control, index) { return control.getControlType() == "subgrid"; });
        if (subgrids.length > 4) for (var i = 4; i < subgrids.length; i++) subgrids[i].refresh();
        blnSuccess = true;
    } catch (e) { }
    if (blnSuccess) clearInterval(refreshSubGridId);
}
12.禁用SubGrid
function disableSubGrid(subGridName) {
    try {
        var subGrid = document.getElementById(subGridName + "_span");
        if (subGrid) subGrid.disabled = true;
    } catch (e) { }
}
13.創建服務
CrmConnection connection = CrmConnection.Parse(CRMConnectionPath);
using (CrmOrganizationServiceContext orgservice = new CrmOrganizationServiceContext(connection))
{
AutoShut(orgservice);
}
14.讓報表取到當前表單的ID:
DS1:
select new_promotionid from filterednew_promotion as crmaf_filterednew_promotion
DS2:
select new_name from filterednew_promotion  where new_promotionid=@proid
對DS2生成的參數@proid-屬性-默認值-DS1
讓報表取到當前用戶ID:
SELECT [dbo].[fn_FindUserGuid]()
select systemuserid,fullname from FilteredSystemUser where systemuserid = dbo.fn_FindUserGuid()
讓報表取到當前用戶ID:
select businessunitid,name from businessunit where businessunitid = dbo.fn_FindBusinessGuid()


15.執行工作流
ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
{
WorkflowId = new Guid("C4745DA5-CA92-4E37-9A63-0F3BC73ECB06"),
EntityId = new Guid("C68B84F8-D397-E311-93FD-002481E8832E")
};
ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)testService.OrganizationService.Execute(request);


16.多對對,N對N,添加關系:
EntityReferenceCollection coll=new EntityReferenceCollection();
coll.Add(new EntityReference("systemuser",new Guid("1DCCAD1E-9F67-E311-93EF-002481E88330")));
testService.Associate("team", new Guid("99C72A6E-EA71-E311-93FD-002481E8832E"), new Relationship("teammembership_association"), coll);
已存在關系,會報錯。

 

Microsoft Dynamics CRM 2011 JavaScript Development Cheat Sheet              

一、Xrm.Page.context Methods

1.getAuthenticationHeader  獲取認證表頭

已棄用。 Returns the encoded SOAP header necessary to use Microsoft Dynamics CRM 4.0 web service calls using Microsoft JScript. 已棄用。需要使用Microsoft JScript中使用的Microsoft Dynamics CRM 4.0中的Web服務調用返回編碼的SOAP頭。

2.getCurrentTheme  獲取當前主題。

Returns the current user’s Outlook theme  返回當前用戶outlook的主題。

3.getOrgLcid  獲取組織語言id。

Returns the LCID value for the base language of the organization 返回的基本語言的組織的LCID的值。

4.getOrgUniqueName  獲取組織唯一的名稱。

Returns the unique organizations name 返回唯一的組織名稱

5.getQueryStringParameters   獲取查詢字符串參數。

Returns an array of key-value pairs representing the query strings  返回一個數組的表示查詢字符串的鍵值對。

6.getServerUrl  獲取服務器url地址。

Returns the base server URL 返回基本服務器url地址。

7.getUserId  獲取當前的用戶ID。

Returns the current user’s SystemUser id  返貨當前用戶的系統用戶的id。

8.getUserLcid   獲取用戶語言id。 注意LCID 解釋:http://baike.baidu.com/view/1203977.htm

Returns the LCID value representing the user’s preferred language  返回表示用戶首選語言的LCID值。

9.getUserRoles 獲取用戶角色。

Returns an array of GUID values of the security roles the user is associated with 返回與用戶的安全角色關聯的GUID值的一個數組。

10.isOutlookClient 是outlook客戶端。

Returns a Boolean value indicating if the user is using Outlook  說明返回一個布爾值,如果用戶使用的是Outlook。

11.isOutlookOnline 是outlook在線

Returns a Boolean value indicating if the user is connected to the server while using MSCRM for Outlook with Offline Access.  

返回一個布爾值,表示如果用戶連接到服務器,而使用MSCRM為Outlook中使用離線訪問。

12.prependOrgName 前置組織名稱。

Prepends the organization name to the specified pathclient 組織名稱預先考慮到指定的路徑客戶端。

 二、Xrm.Page.data.entity attribute Methods

   Method(方法)                                       Applicable(可適用)           Description(描述)


  1.addOnChange(添加OnChange)             All(所有)                    Sets a function to be called when the value is changed 設置值被改變時被調用的函數
  2.fireOnChange(解除OnChange)              All(所有)                    Causes the OnChange even t to occur on the attribute  引起OnChange事件發生的屬性                                                          

  3.getAttributeType(獲取屬性的類型)         All(所有)                    Returns the type of attribute (string)  返回屬性(字符串)的類型

  contentIFrame.Xrm.Page.data.entity.attributes.get("name").getAttributeType()  相當於 contentIFrame.Xrm.Page.getAttribute("name").getAttributeType();

相當於contentIFrame.Xrm.Page.getControl("name").getAttribute("name").getAttributeType(); 

  注意:在IE瀏覽器上調試的時候,必需加contentIFrame.

 4.getFormat(獲取格式)                           All(所有)                    Returns formatting options for the attribute (string)  返回的格式選項集的屬性(字符串)

  5.getInitialValue(獲取初始值)   boolean(布爾), optionset(選項集) Returns the initial value for Boolean or optionset attributes返回布爾或選項集屬性的初始值

  6.getIsDirty(獲取是否變化)     All(所有) Returns a Boolean value indicating if there are unsaved changes to the attribute value 如果有未保存的更改的屬性值,則說明返回一個布爾值。

  7.getMax(獲取最大值)     money(貨幣), decimal(十進制), integer(整型), double(雙進度型)       Returns the maximum allowed value for an attribute (number)  返回屬性(數字)的最大允許值。

 8.getMaxLength(獲取最大長度)   string(字符串), memo(備忘錄)  Returns the maximum length of an attribute (number) 返回屬性(數字)的最大允許值的長度。

 9.getMin(獲取最大值)     money(貨幣), decimal(十進制), integer(整型), double(雙進度型)       Returns the minimumallowed value for an attribute (number)  返回屬性(數字)的最小允許值。

10.getName(獲取名稱)                     All(所有)                              Returns the logical name of the attribute 返回屬性的邏輯名稱

11.getOption(獲取選項)                  optionset(選項集)                  Returns an option object by matching its name  返回他的名稱相匹配的一個選項對象

12. getOptions(獲取選項集)            optionset(選項集)                   Returns an array of options for an optionset attribute 返回一個選項集屬性的選項集的一個數組

13.getParent(獲取父對象)                     All(所有)                             Returns the parent object to the attribute 返回屬性的父對象

14.getPrecision(獲取精度)   money(貨幣), decimal(十進制), integer(整型), double(雙進度型) Returns the number of digits allowed after the decimal point 返回允許小數點后的數字的位數。

15.getRequiredLevel(獲取所需級別)         All(所有)             Returns a string indicating whether the attribute is required or recommended 返回一個字符串,指示屬性是必需或推薦

16.getSelectedOption(獲取選擇項集)       optionset(選項集) Returns the option selected in an optionset attribute.返回一個選項集屬性的所選擇的選項。

17.getSubmitMode(獲取提交模式)         All(所有)            Returns a string indicating if the attribute will be submitted when the record is saved 當記錄保存的時候,如果這個屬性將會被提交,返回一個字符串提示。

18.getText(獲取文本)   optionset(選項集)  Returns the selected option for an optionset attribute  返回所選的選項為一個選項集的屬性               

19.getUserPrivilege(獲取用戶權限)  All(所有) Returns an array of Boolean values indicating if the user can create/read/update an attribute's values 返回一個布爾值數組,表示如果用戶可以創建/讀取/更新屬性的值。

20.getValue(獲取值)  All(所有)Retrieves the data value for an attribute 檢索一個屬性的數據的值

21.removeOnChange(移除OnChange) All(所有) Removes a function from the OnChange event handler 移除來自onChange事件處理的一個函數。

22.setRequiredLevel(設置必需級別)       All(所有)Sets whether the attribute is required or recommended 設置是否這個屬性是必需還是推薦。

23.setSubmitMode(設置提交模式)           All(所有) Sets whether the attribute’s data will be submitted  設置是否這個屬性的數據將會被提交。
24.setValue(設置值)                               All(所有) Sets the data value for an attribute. 為一個屬性設置數據值。

 

三、Form Event Handler Execution Context Reference 

1.getContext(獲取上下文)    Returns the Xrm.Page.context object 返回Xrm.Page.context的對象。
2.getDepth(獲取深度)          Returns a value indicating the order in which this handler is executed 返回一個值,指示此處理程序執行的順序。
3.getEventArgs(獲取事件參數) Returns an object with methods to manage the Save event 返回一個對象,使用方法來管理保存事件。
4.getEventSource(獲取事件源)               Returns a reference to the object that the event occurred on 返回一個對象的引用,事件是發生在。
5.getSharedVariable(獲取共享變量)                              Retrieves a variable set using setSharedVariable 獲取變量的使用,設置共享變量 。
6.setSharedVariable Sets the value of a variable to be used by a hander after the current completes

 

三、Shortcut methods

Shortcut(快捷)                                            Equivalent (等價於)
Xrm.Page.getAttribute                         Xrm.Page.data.entity.attributes.get 
Xrm.Page.getControl                            Xrm.Page.ui.controls.get 
GetGlobalContext (Web Resources)       Xrm.Page.context (within forms)

比如:

獲取字段名為name的值

contentIFrame.Xrm.Page.getAttribute("name").getValue() 相當於 

contentIFrame.Xrm.Page.data.entity.attributes.get("name").getValue()

 

contentIFrame.Xrm.Page.getControl("name").getAttribute("name").getValue();相當於

contentIFrame.Xrm.Page.ui.controls.get("name").getAttribute("name").getValue(); 

                                                                                 

四、Xrm.Page.data.entity Methods

獲取字段的值 

contentIFrame.Xrm.Page.data.entity.attributes.get("name").getValue();

1.addOnSave            Sets a function to be called when the record is saved 
2.getDataXml           Returns the xml string to be sent to the server when the record is saved 
3.getEntityName         Returns the logical name of the entity for the record 
4.getId                    Returns GUID id value for the record 
5.getIsDirty              Returns a Boolean value indicating if any fields in the form have been modified 
6.removeOnSave        Removes a function from the OnSave event hander 
7.save                      Saves the record

五、

前台獲取lookup字段值: contentIFrame.window.Xrm.Page.getAttribute("new_costfrom").getValue()[0].id 
獲取當前登錄用戶:Xrm.Page.context.getUserId()
獲得當前頁面類型:Xrm.Page.ui.getFormType() 
獲得當前實體名稱:contentIFrame.Xrm.Page.data.entity.getEntityName()
刷新Ribbon工具條:Xrm.Page.ui.refreshRibbon();
給lookup字段賦值:var tmp=[{ id: PaymentInfo.new_distributor.Id, 
name: PaymentInfo.new_distributor.Name, 
typename: PaymentInfo.new_distributor.LogicalName}];
Xrm.Page.getControl("new_budget").getAttribute().setValue(tmp);
js查詢方法
function Form_CheckSoluInfo() {
if(Xrm.Page.data.entity.getEntityName() == 'new_po_exp_detail')
{
return true;
}
var rest = new fwREST();
var soluInfo = rest.get("New_promotion_peSet(guid'" + Xrm.Page.getAttribute("new_pe_exp_detail").getValue()[0].id +
"')?$select=New_approvestate,New_f_type,new_current_approver");
var value = getEnabledValueForCheckSoluInfo(soluInfo.New_approvestate.Value, soluInfo.New_f_type.Value, "{" + soluInfo.new_current_approver.Id + "}");
return value;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM