我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面的微软最有价值专家(Microsoft MVP),欢迎关注我的微信公众号 MSFTDynamics365erLuoYong ,回复405或者20200424可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!
有时候经常碰到子网格的添加按钮需要根据父记录的状态来隐藏,比如只有订单是草稿状态的状态下才能显示订单行的添加按钮,这里我用编辑实体的子网格按钮来控制。
将子网格对应实体添加到解决方案中后用Ribbon Workbench打开。找到该实体的Subgrid 命令栏,对【ADD NEW {0}】 和 【ADD EXISTING {0}】两个按钮都做同样操作。
右击,选择【Customize Command】菜单项目,我的截图是灰色的是因为我之前点击过了,你没有点击过的话应该是可以选择的。
可以看到这两个按钮的id分别类似 Mscrm.SubGrid.new_orderitems.AddNewStandard 和 Mscrm.SubGrid.new_orderitems.AddExistingStandard 。
然后为他们的命令添加一个相同的Enable Rule,类型为 Custom Rule,我这里设置如下:
我使用的JavaScript代码是
"use strict"; var LuoYong = window.LuoYong || {}; LuoYong.OrderItemRibbon = LuoYong.OrderItemRibbon || {}; (function () { this.subgridCreateEnableRule = function (primaryControl) { var formContext = primaryControl; var statusCode = formContext.getAttribute("statuscode").getValue(); if (statusCode === 1) { return true; } else { return false; } } }).call(LuoYong.OrderItemRibbon); //# sourceURL=orderitem_ribbon.js
这样发布后的效果是看不到新建或者添加按钮了:
下图是修改之前的效果:
当然可以通过别的方式来添加该订单的订单行,如果要完全限制住不能添加请用插件,比如将如下的代码注册到订单行实体的Pre Create中。
using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; using System; namespace DemoPlugins { public class orderitemsprecreate : IPlugin { public void Execute(IServiceProvider serviceProvider) { //获取日志服务 ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); //写一些日志,方便跟踪 tracingService.Trace($"Enter {this.GetType().ToString()} on {DateTime.UtcNow.ToString()}"); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { //插件针对的当前实体记录,对于Pre Create来讲,该对象包括了所有设置的字段值,若字段没有设置值,在该对象中会不存在 Entity currentEntity = (Entity)context.InputParameters["Target"]; //获取组织服务 IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService orgSvc = serviceFactory.CreateOrganizationService(context.UserId); if (currentEntity.Contains("new_orderid") && currentEntity.GetAttributeValue<EntityReference>("new_orderid") != null) { var orderEntity = orgSvc.Retrieve("new_order", currentEntity.GetAttributeValue<EntityReference>("new_orderid").Id, new ColumnSet("statuscode")); if(orderEntity.GetAttributeValue<OptionSetValue>("statuscode").Value != 1) { throw new InvalidPluginExecutionException("所属订单非草稿状态,不允许增加订单行!"); } } else { throw new InvalidPluginExecutionException("所属订单必须输入!"); } } tracingService.Trace($"Leave {this.GetType().ToString()} on {DateTime.UtcNow.ToString()}"); } } }
这样的话,通过其他方式添加也会报错,界面上的效果如下: