AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Разработка
CRM
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск Все разделы прочитаны

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 28.10.2020, 18:55   #1  
Ion is offline
Ion
Участник
 
332 / 16 (1) ++
Регистрация: 19.12.2012
CRM UCI Ribbon - Show/Hide Word Template Items
Добрый день!

Есть задача: необходимо показывать шаблоны документов для opportunity исходя из ее типа. То есть для каждого типа opportunity будет свой набор доступных шаблонов.

Не знаю можно ли как-то фильтровать то что есть в рибоне для кнопки Word Template.
Если нет, тогда делать кастомную логику и кнопки, правда надо будет генерировать документ и скачивать его на UI.

Есть ли еще какие-то варианты как эту задачу можно решить.

Благодарен!
Старый 28.10.2020, 22:24   #2  
a33ik is offline
a33ik
Чайный пьяница
Аватар для a33ik
MCP
MCBMSS
Злыдни
Соотечественники
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,243 / 896 (36) +++++++
Регистрация: 02.07.2008
Адрес: Greenville, SC
Кастомизируйте команду выпадающего списка при помощи Ribbon Workbench и подпилите под ваши нужды вычитывание документов.
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством.

Подписывайтесь на мой блог, twitter и YouTube канал.
Пользуйтесь моим Ultimate Workflow Toolkit
Старый 02.11.2020, 15:47   #3  
Ion is offline
Ion
Участник
 
332 / 16 (1) ++
Регистрация: 19.12.2012
Цитата:
Сообщение от a33ik Посмотреть сообщение
Кастомизируйте команду выпадающего списка при помощи Ribbon Workbench и подпилите под ваши нужды вычитывание документов.
Есть нюансы, там flyout, а я не знаю как с ним работать, то есть список динамический.
Старый 02.11.2020, 21:38   #4  
a33ik is offline
a33ik
Чайный пьяница
Аватар для a33ik
MCP
MCBMSS
Злыдни
Соотечественники
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,243 / 896 (36) +++++++
Регистрация: 02.07.2008
Адрес: Greenville, SC
Цитата:
Сообщение от Ion Посмотреть сообщение
Есть нюансы, там flyout, а я не знаю как с ним работать, то есть список динамический.
Кастомизируете команду выпадающего списка, получаете команду, которая используется для заполнения списка, смотрите функцию, которая вызывается при генерации списка, делаете то же самое но с учетом фильтрации, которая вам необходима, подменяете стандартную функцию вашей кастомной. Публикуете. Я бы двигался таким курсом.

Как альтернатива... Я бы просто спрятал стандартный выпадающий список и добавил бы свою кастомную. Как то так.
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством.

Подписывайтесь на мой блог, twitter и YouTube канал.
Пользуйтесь моим Ultimate Workflow Toolkit
За это сообщение автора поблагодарили: Ion (1).
Старый 04.11.2020, 11:37   #5  
Ion is offline
Ion
Участник
 
332 / 16 (1) ++
Регистрация: 19.12.2012
Цитата:
Сообщение от a33ik Посмотреть сообщение
Кастомизируете команду выпадающего списка, получаете команду, которая используется для заполнения списка, смотрите функцию, которая вызывается при генерации списка, делаете то же самое но с учетом фильтрации, которая вам необходима, подменяете стандартную функцию вашей кастомной. Публикуете. Я бы двигался таким курсом.

Как альтернатива... Я бы просто спрятал стандартный выпадающий список и добавил бы свою кастомную. Как то так.
Спасибо, нашел в Main_system_library методы generateWordTemplateFlyout, runWordTemplate - все то что нужно!
Старый 04.11.2020, 13:06   #6  
Ion is offline
Ion
Участник
 
332 / 16 (1) ++
Регистрация: 19.12.2012
Цитата:
Сообщение от Ion Посмотреть сообщение
Спасибо, нашел в Main_system_library методы generateWordTemplateFlyout, runWordTemplate - все то что нужно!
Вот эти функции, по сути если кому-то надо будет, по можно просто подпилить функцию generateExcelTemplateFlyout и добавить нужные фильтры.
X++:
var CustomXrmCore;
(function(CustomXrmCore) {
    var Commands;
    (function(Commands) {
        var ExportLibrary = function() {
            function ExportLibrary() {
                var _this = this;
                this.generateWordTemplateFlyout = function(commandProperties, entityTypeName, isForm, gridControl) {

                    var documentType = 2
                      , ribbonRelationshipType = -1
                      , contextType = 0
                      , currentEntityTypeName = entityTypeName;
                    if (isForm)
                        contextType = 1;
                    else {
                        if (entityTypeName == "activitypointer" && gridControl != null && gridControl.getGrid() != null) {
                            var selectedRows = gridControl.getGrid().getSelectedRows();
                            if (selectedRows != null && selectedRows.getLength() == 1) {
                                var selectedEntity = selectedRows.get(0).data.entity;
                                if (selectedEntity != null)
                                    currentEntityTypeName = selectedEntity.getEntityName()
                            }
                        }
                        if (typeof gridControl.getRelationship === "function") {
                            contextType = 2;
                            var relationship = gridControl.getRelationship();
                            if (relationship !== null && relationship.relationshipType === 0)
                                ribbonRelationshipType = 0;
                            else if (relationship !== null && relationship.relationshipType === 1)
                                ribbonRelationshipType = 1
                        }
                    }
                    var deferred1 = XrmCore.InternalUtilities.ExportUtilities.retrieveSystemDocumentTemplates(currentEntityTypeName, documentType)
                      , deferred2 = XrmCore.InternalUtilities.ExportUtilities.retrievePersonalDocumentTemplates(currentEntityTypeName, documentType)
                      , menu = Promise.all([deferred1, deferred2]).then(function(_a) {
                        var systemTemplates = _a[0]
                          , personalTemplates = _a[1];
                        ExportLibrary._systemTemplates = systemTemplates;
                        ExportLibrary._personalTemplates = personalTemplates;
                        return _this.buildMenu(systemTemplates, personalTemplates, entityTypeName, isForm, contextType, ribbonRelationshipType, documentType)
                    });
                    commandProperties["PopulationXML"] = menu;
                    return
                }
                ;
                this.generateExcelTemplateFlyout = function(commandProperties, entityTypeName, gridControl) {
                    var isForm = false
                      , documentType = 1
                      , contextType = 0
                      , ribbonRelationshipType = -1
                      , currentEntityTypeName = entityTypeName;
                    if (entityTypeName == "activitypointer" && gridControl != null && gridControl.getEntityName() != null)
                        currentEntityTypeName = gridControl.getEntityName();
                    if (typeof gridControl.getRelationship === "function") {
                        contextType = 2;
                        var relationship = gridControl.getRelationship();
                        if (relationship !== null && relationship.relationshipType === 0)
                            ribbonRelationshipType = 0;
                        else if (relationship !== null && relationship.relationshipType === 1)
                            ribbonRelationshipType = 1
                    }
                    var deferred1 = XrmCore.InternalUtilities.ExportUtilities.retrieveSystemDocumentTemplates(currentEntityTypeName, documentType)
                      , deferred2 = XrmCore.InternalUtilities.ExportUtilities.retrievePersonalDocumentTemplates(currentEntityTypeName, documentType)
                      , menu = Promise.all([deferred1, deferred2]).then(function(_a) {
                        var systemTemplates = _a[0]
                          , personalTemplates = _a[1];
                        ExportLibrary._systemTemplates = systemTemplates;
                        ExportLibrary._personalTemplates = personalTemplates;
                        return _this.buildMenu(systemTemplates, personalTemplates, entityTypeName, isForm, contextType, ribbonRelationshipType, documentType)
                    });
                    commandProperties["PopulationXML"] = menu;
                    return
                };
                this.openDocTemplateDialog = function(dialogName, documentType, gridControl, isForm) {
                    var width = 512
                      , height = 300
                      , docDialog = "DocumentTemplateUpload";
                    if (documentType == 2 && dialogName === "DownloadTemplate") {
                        width = 850;
                        height = 650
                    }
                    if (dialogName === "DownloadTemplate")
                        docDialog = "DocumentTemplateDownload";
                    var params = {};
                    if (isForm)
                        params["Entity_Name"] = gridControl.entityReference.entityType;
                    else {
                        var viewId = gridControl.getViewSelector().getCurrentView().id.replace("{", "").replace("}", "")
                          , currentView = gridControl.getViewSelector().getCurrentView().name
                          , fetchXmlData = gridControl.getFetchXml();
                        params["Entity_Name"] = gridControl.getEntityName();
                        params["View_Id"] = viewId;
                        params["current_view"] = currentView;
                        params["fetch_xmldata"] = fetchXmlData
                    }
                    params["DocTemplateFile_Type"] = documentType;
                    params["DocTemplate_ExpectedFileType"] = documentType == 1 ? 3 : documentType;
                    params["DocTemplate_Type"] = 9941;
                    Xrm.Navigation.openDialog(docDialog, {
                        width: width,
                        height: height,
                        position: 1
                    }, params).then(function(result) {
                        if (result.parameters && result.parameters["Is_DocumentTemplate_Uploaded"] != undefined && result.parameters["DocumentTemplate_index"] != undefined)
                            if (result.parameters["Is_DocumentTemplate_Uploaded"] == 1) {
                                var entityFormOptions = {};
                                entityFormOptions["entityName"] = "personaldocumenttemplate";
                                entityFormOptions["entityId"] = result.parameters["DocumentTemplate_index"];
                                var actionDescriptor = {
                                    actionLabel: Xrm.Utility.getResourceString("Main_system_library", "View_Personal_Document_Template"),
                                    eventHandler: function() {
                                        Xrm.Navigation.openForm(entityFormOptions)
                                    }
                                };
                                Xrm.UI.addGlobalNotification(1, 1, Xrm.Utility.getResourceString("Main_system_library", "DocTemplate_Successfully_Uploaded"), null, actionDescriptor)
                            }
                        Xrm.Utility.closeProgressIndicator()
                    });
                    return
                }
                ;
                this.runWordTemplate = function(commandProperties, entityTypeCode, gridControl, selectedRecords) {

                    var isForm = false
                      , records = [];
                    if (typeof selectedRecords === "string") {
                        records = [selectedRecords];
                        isForm = true
                    } else
                        records = [selectedRecords[0].Id];
                    var documentType = 2
                      , openMode = {
                        openMode: 2
                    }
                      , personalTemplateKeyword = "WordTemplates.Menu.PersonalWordTemplates."
                      , sourceControlId = commandProperties["SourceControlId"];
                    if (sourceControlId == "ViewAllMyTemplatesId") {
                        _this.navigateToPersonalDocumentTemplates("recordlist", "personaldocumenttemplate");
                        return
                    }
                    var templateEntityName = "documenttemplate";
                    if (sourceControlId.indexOf(personalTemplateKeyword) !== -1)
                        templateEntityName = "personaldocumenttemplate";
                    var templateId = sourceControlId.split(/[. ]+/).pop();
                    if (templateId === "UploadTemplate" || templateId === "DownloadTemplate") {
                        _this.openDocTemplateDialog(templateId, documentType, gridControl, isForm);
                        return
                    }
                    var templateRef = {
                        id: "{" + templateId + "}",
                        entityType: templateEntityName
                    }
                      , actualEntityTypeCode = isForm ? entityTypeCode : Xrm.Internal.getEntityCode(selectedRecords[0].TypeName)
                      , recordsString = JSON.stringify(records)
                      , exportWordDocumentRequest = new XrmCore.SdkContracts.ExportWordDocumentRequest(actualEntityTypeCode,templateRef,recordsString);
                    Xrm.Utility.showProgressIndicator(Xrm.Utility.getResourceString("Main_system_library", "ExportToDocx_ProgressDialog_Header"));
                    var deferred = Xrm.WebApi.online.execute(exportWordDocumentRequest).then(function(res) {
                        return res.json()
                    }).then(function(odataResponse) {
                        var template = undefined;
                        if (templateEntityName === "documenttemplate")
                            template = ExportLibrary._systemTemplates.filter(function(obj) {
                                return obj.Id === templateId
                            })[0];
                        else
                            template = ExportLibrary._personalTemplates.filter(function(obj) {
                                return obj.Id === templateId
                            })[0];
                        var file = {
                            fileContent: odataResponse.WordFile,
                            fileName: XrmCore.InternalUtilities.ExportUtilities.generateExportFileName(template.Name, documentType),
                            mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        };
                        Xrm.UI.addGlobalNotification(1, 1, Xrm.Utility.getResourceString("Main_system_library", "Menu_Label_Group_Word_SucessfullyDownloaded"), null, null);
                        return Xrm.Navigation.openFile(file, openMode)
                    }, function(errorResponse) {
                        Xrm.Utility.closeProgressIndicator();
                        console.log(errorResponse);
                        var errorMessage = "";
                        if (errorResponse.innerror && errorResponse.innerror.message) {
                            if (errorResponse.innerror.message != "")
                                errorMessage = errorResponse.innerror.message
                        } else
                            errorMessage = errorResponse.message;
                        var errorDialogOptions = {
                            message: errorMessage,
                            errorCode: errorResponse.errorCode
                        };
                        Xrm.Navigation.openErrorDialog(errorDialogOptions)
                    }).then(function(res) {
                        console.log(res);
                        Xrm.Utility.closeProgressIndicator()
                    });
                    return
                }
                ;
                this.navigateToPersonalDocumentTemplates = function(pageType, entityName) {
                    var personalDocTemplatePageInput = {
                        pageType: pageType,
                        entityName: entityName
                    };
                    Xrm.Navigation.navigateTo(personalDocTemplatePageInput)
                }
                ;
                this.buildMenu = function(systemTemplates, personalTemplates, entityTypeName, isForm, contextType, ribbonRelationshipType, documentType) {
                    var menuId = XrmCore.InternalUtilities.ExportUtilities.determineRibbonMenuId(entityTypeName, isForm, contextType, ribbonRelationshipType, documentType, false)
                      , onlineMenuId = XrmCore.InternalUtilities.ExportUtilities.determineRibbonMenuId(entityTypeName, isForm, contextType, ribbonRelationshipType, documentType, true)
                      , commandId = XrmCore.InternalUtilities.ExportUtilities.determinRibbonCommandId(entityTypeName, isForm, contextType, ribbonRelationshipType, documentType, false)
                      , systemButtonsControl = systemTemplates != null ? XrmCore.InternalUtilities.ExportUtilities.buildControlsFromTemplates(menuId, onlineMenuId, commandId, systemTemplates, true, documentType) : null
                      , personalButtonsControl = personalTemplates != null ? XrmCore.InternalUtilities.ExportUtilities.buildControlsFromTemplates(menuId, onlineMenuId, commandId, personalTemplates, false, documentType) : null
                      , createcommandId = XrmCore.InternalUtilities.ExportUtilities.determinCreateRibbonCommandId(entityTypeName, isForm, contextType, documentType, true)
                      , createTemplates = XrmCore.InternalUtilities.ExportUtilities.retrieveCreateTemplates()
                      , createuploadDownloadButtonsControl = XrmCore.InternalUtilities.ExportUtilities.buildControlsForCreate(menuId, createcommandId, createTemplates, false, documentType)
                      , menuSection1 = XrmCore.InternalUtilities.ExportUtilities.buildMenuSection(menuId, false, documentType, true, 10, createuploadDownloadButtonsControl)
                      , menuSection2 = systemButtonsControl != null ? XrmCore.InternalUtilities.ExportUtilities.buildMenuSection(menuId, true, documentType, false, 20, systemButtonsControl) : null
                      , menuSection3 = personalButtonsControl != null ? XrmCore.InternalUtilities.ExportUtilities.buildMenuSection(menuId, false, documentType, false, 30, personalButtonsControl) : null
                      , menuSections = [];
                    menuSections.push(menuSection1);
                    menuSection2 != null && menuSections.push(menuSection2);
                    menuSection3 != null && menuSections.push(menuSection3);
                    var menu = XrmCore.InternalUtilities.ExportUtilities.buildMenu(menuId, menuSections);
                    return menu
                }
				return {
					RunWordTemplate: runWordTemplate,
					GenerateWordTemplateFlyout: generateWordTemplateFlyout
				}
            }
			ExportLibrary = ExportLibrary();
            ExportLibrary._systemTemplates = [];
            ExportLibrary._personalTemplates = [];
            return ExportLibrary;
        }();
        Commands.ExportLibrary = ExportLibrary
    }
    )(Commands = CustomXrmCore.Commands || (CustomXrmCore.Commands = {}))
}
)(CustomXrmCore || (CustomXrmCore = {}));
За это сообщение автора поблагодарили: a33ik (1).
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2013 Update Rollup 2 Blog bot Dynamics CRM: Blogs 0 15.04.2014 01:15
crminthefield: Podcast and Overview: Microsoft Dynamics CRM 2011 Update Rollup 12 Blog bot Dynamics CRM: Blogs 0 30.01.2013 01:11
crminthefield: CRM Upgrade Best Practices Blog bot Dynamics CRM: Blogs 0 11.10.2012 00:11
CRM Programmer: How to hide an items of drop-down list? Blog bot Dynamics CRM: Blogs 0 10.11.2009 14:05
CRM DE LA CREME! Configuring Microsoft Dynamics CRM 4.0 for Internet-facing deployment Blog bot Dynamics CRM: Blogs 0 18.08.2009 11:05
Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 18:34.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.