需求:
最近有個需求,需要對 sub-grid Add Existing Button [+] 的 Lookup 内容進行過濾,如下圖:
解決方案:
sub-grid Inlie lookup 實際上也是一個普通的 lookup 控件,因此一樣可以支持 lookup 字段的 addPreSearch 和 addCustomFilter 方法,後面我們就通過 JavaScript 利用這兩個方法來實現我們所需的效果。
代碼實現:
1 function fnFilterReceiptInline() { 2 //sub-grid name: grid_receipt_list 3 //[add existing button]: [sub-grid name]_addImageButton 4 var subgirdAddBtnId = "grid_receipt_list_addImageButton"; 5 var subgridAddBtn = document.getElementById(subgirdAddBtnId) || window.parent.document.getElementById(subgirdAddBtnId);//獲取[+]的dom元素 6 if (subgridAddBtn == null) { 7 setTimeout(fnFilterReceiptInline, 1000); 8 return; 9 } 10 11 var getSubgridLookupAndAddFilter = function () { 12 //lookup控件名: lookup_[sub-grid name] 13 var subgridLookup = Xrm.Page.getControl("lookup_grid_receipt_list");//獲取lookup控件 14 if (subgridLookup == null) { 15 setTimeout(getSubgridLookupAndAddFilter, 200); 16 return; 17 } 18 if (subgridLookup.customFilterAdded) { 19 return; 20 } 21 22 //addPreSeach for lookup control 23 subgridLookup.addPreSearch(function () { 24 fnFilterHandler(); 25 }); 26 subgridLookup.customFilterAdded = true; 27 }; 28 //給[+]添加一個click事件:點擊后對lookup控件進行 pre search 29 subgridAddBtn.addEventListener("click", function () { 30 setTimeout(getSubgridLookupAndAddFilter, 200); 31 }); 32 } 33 34 //利用fetch xml 對 lookup control 進行過濾篩選 35 function fnFilterHandler() { 36 var subgridLookup = Xrm.Page.getControl("lookup_grid_receipt_list"); 37 38 var oId = null; 39 var oName = null; 40 var oAccount = Xrm.Page.getAttribute("cus_account_no").getValue(); 41 if (oAccount != null && oAccount[0] != null) { 42 oId = oAccount[0].id.replace("{", "").replace("}", ""); 43 oName = oAccount[0].name; 44 } 45 46 var FilterXML = "<filter type='and'>" 47 + "<condition attribute='cus_account_no' operator='eq' uiname='" 48 + oName + "' uitype='account' value='{" + oId + "}' />" 49 + "</filter>"; 50 if (oName != null && oId != null) { 51 subgridLookup.addCustomFilter(FilterXML); 52 } 53 }
以上代碼的效果:當點擊 [+] 時,js 就會對 Inline-lookup 控件進行 PreSearch,達到所需的過濾效果。
參考博客:https://bernado-nguyen-hoan.com/2017/01/06/apply-filtering-to-subgrids-inline-lookup-in-crm/