• Dynamic CRM操作大全


    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.data.refresh(true);

     

    禁用页面所有控件:

    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 = '';

            var view = '';

            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 Registration Tool => Profile => 保存ErrorDetail.txt => Stop Profile => Debug,加载ErrorDetail.txt和DLL => VS附加PlugRegistration.exe到进程 =>Debug Start

    11.插件抛异常到页面:throw new InvalidPluginExecutionException("");

    12.插件取值:

    int statuscode = (targer.Attributes["statuscode"] as OptionSetValue).Value;//targer为获取的实体上下文信息,且该值只能获取页面修改后的信息

    13.插件删除了类文件,还需要去RegisterFile.crmregister删除对应的引用,否则会出现部署失败

    14.高级查找-编辑列-F12未出现开发人员工具:IE-Internet选项-安全-Internet-自定义级别-允许网站打开没有地址或状态栏的窗口-禁用

    15.是否出现“添加已存在**明细”按钮方法:明细表中主表字段的必填等级=业务必须,则不出现添加已存在按钮,否则出现。

    16.删除一个表数据,在Pre-Delete中,已经把与之关联的数据中包含它的字段都NULL了。查询与之关联的数据,不能再通过该字段。

    17.货币类型后台赋值:new Money(decimal.Parse())

    18.菜单关联视图:

    【函数】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.插件相关操作

    获取实体:

    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.服务器复合查询

    //根据客户ID获取客户类型

    private int GetAccounttypeById(Guid accountId, IOrganizationService service)

    {

    int yto_accounttype = 0;

    string fetchxml = @"

     

     

     

     

     

     

     

    ";

    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查询的分组和统计

     

     

     

    取值

     (((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: '',

            layoutXml: '',

            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 + " ";

    } else {

    msg += "单据[" + objs[0].yto_name + "]审批成功" + "/n";

    }

    });

     

     

    6.添加了审批流的实体,在状态变更的时候获取的上下文登陆人是system,根据顶级上下文获取当前真实登陆人:

    ///

    /// 获取最顶级插件上下文对象

    ///

    ///当前插件上下文对象

    /// 返回最顶级插件上下文对象

    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.getClientUrl()获取服务器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

    setSharedVariable设置处理程序在当前完成后要使用的变量的值

     

    三、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);

     

  • 相关阅读:
    SQL函数union,union all整理
    Oracle中的having()函数
    SQL函数count(),sum()理解
    Office Online Server 和 SharePoint 2016配置时报错
    Manjaro 黑苹果网卡BCM4360折腾记
    Manjaro安装与基本配置
    在Arch Linux/Manjaro上安装KVM、QEMU和Virt Manager的方法
    Nginx 优化详解
    xargs 使用详解
    Centos7 搭建lnmp环境 (centos7+nginx+MySQL5.7.9+PHP7)
  • 原文地址:https://www.cnblogs.com/LanHai12/p/15257802.html
Copyright © 2020-2023  润新知