Добрый день!
Есть небольшая задача:
1) по нажатию кнопки открывается всплывающее окно с возможностью оставить комментарии в ленту
2) после нажатия ОК - окно закрывается и комментарий добавляется в ленту этого объекта
Пока просто даже не представляю с какой стороны подойти к выполнению этого кейса. Кнопку реализовал и она работает, надо именно процесс отображения окна и сохранение комментария прописать.
По примеру, понимаю что можно сделать обычное модальное окно, но используя обычный пример выдается ошибка: ModalBox.show is not a function
Единственное где используется:
var renderTo = ModalBox.show(config, function()
{sandbox.unloadModule(moduleId, renderTo); });Или пример корявый или где-то что-то надо еще делать. Сам пример: https://community.terrasoft.ru/articles/prosteisee-modalnoe-okno-modalb…
Нравится
2) Как то так значение полей подберите сами
var insert = Ext.create("Terrasoft.InsertQuery", {
rootSchemaName: "SocialMessage"
});
insert.setParameterValue("Message", data.message, Terrasoft.DataValueType.TEXT);
if (data.entityId) {
insert.setParameterValue("EntitySchemaUId", data.entitySchemaId, Terrasoft.DataValueType.GUID);
insert.setParameterValue("EntityId", data.entityId, Terrasoft.DataValueType.GUID);
}
insert.execute(function(result) {
if (result.success) {
//чтото делаем если успешно добавлена запись
});
}
Могу предложить по сути то же, что и в той теме, но чуть более расписанное, для понимания:
Модальное окно состоит из 3 частей.
Часть 1.
Указываем define
define("DocumentPageV2", ["ServiceHelper", "ModalBox", "ModalBoxSchemaModule"],
function(ServiceHelper, ModalBox, resources) {
Вызов данного окна в нужной нам части:
Вызываем например по кнопке.
{
"operation": "insert",
"name": "createActivity",
"values": {
"itemType": 5,
"visible": true,
"caption": "Создать активности",
"click": {
"bindTo": "createActivity"
},
"layout": {
"column": 2,
"row": 1,
"colSpan": 1
}
},
"parentName": "ActionDashboardContainer",
"propertyName": "items",
"index": 0
},
Затем в самом методе вызываем окно, так же можно повесить дополнительный функционал:
onMyClick: function() {
this.openTransactionPage();
},
добавляем методы:
openTransactionPage: function() {
this.sandbox.loadModule("ModalBoxSchemaModule", {
id: this.getTransactionPageId()
});
},
getTransactionPageId: function() {
return this.sandbox.id + "_OpModalPageDateTO";
}
subscribeSandboxEvents: function() {
debugger;
this.callParent(arguments);
this.sandbox.subscribe("DataFromModal", function(arg) {
console.log("msg from modal: " + arg.test);
}, this, [this.sandbox.id + "_" + "OpModalBoxSchemaModule"]);
this.sandbox.subscribe("ButtonClose", function() {
var moduleName = "OpModalBoxSchemaModule";
var moduleId = this.sandbox.id + "_" + moduleName;
var config = {
heightPixels: 420,
widthPixels: 750
};
var renderTo = ModalBox.show(config, function() {
sandbox.unloadModule(moduleId, renderTo);
});
this.sandbox.unloadModule(moduleId, renderTo);
this.sandbox.unsubscribePtp("ButtonClose");
ModalBox.close(true);
}, this, [this.getTransactionPageId()]);
this.sandbox.subscribe("GetModuleInfo", function() {
return {
schemaName: "OpModalPageDateTO"
};
}, this, [this.getTransactionPageId()]);
},
onEntityInitialized: function() {
this.callParent(arguments);
},
Часть 2.
Создаем новый модуль. Наследуемся от "Базовый модуль схемы ( NUI )"
define("OpModalBoxSchemaModule", ["ModalBox", "BaseSchemaModuleV2"],
function(ModalBox) {
Ext.define("Terrasoft.configuration.OpModalBoxSchemaModule", {
extend: "Terrasoft.BaseSchemaModule",
alternateClassName: "Terrasoft.OpModalBoxSchemaModule",
messages: {
"ButtonClose": {
"mode": this.Terrasoft.MessageMode.PTP,
"direction": this.Terrasoft.MessageDirectionType.SUBSCRIBE
}
},
CloseModalBox: function() {
this.callParent(arguments);
},
subscribeSandboxEvents: function() {
this.callParent(arguments);
this.sandbox.subscribe("ButtonClose", function() {
this.sandbox.unloadModule("ModalBoxSchemaModule");
}, this, [this.getTransactionPageId()]);
},
init: function() {
this.callParent(arguments);
},
/**
* @inheritDoc Terrasoft.BaseSchemaModule#generateViewContainerId
* @overridden
*/
generateViewContainerId: false,
/**
* @inheritDoc Terrasoft.BaseSchemaModule#initSchemaName
* @overridden
*/
initSchemaName: function() {
this.subscribeSandboxEvents();
this.schemaName = "OpDateTO";
},
/**
* @inheritDoc Terrasoft.BaseSchemaModule#initHistoryState
* @overridden
*/
initHistoryState: Terrasoft.emptyFn
});
return Terrasoft.OpModalBoxSchemaModule;
});
Часть 3. Создаем карточку модального окна, которое мы увидим, при вызове.
В качестве родителя для модуля указываем "Базовая схема модального окна ( NUI )"
Так же, необходимо создавать свои контейнеры, чтобы в них размещать необходимые нам поля.
define("OpModalPageDateTO", ["ServiceHelper", "ModalBox"], function(ServiceHelper, ModalBox) {
return {
entitySchemaName: "OpDateTO",
details: /**SCHEMA_DETAILS*/{}/**SCHEMA_DETAILS*/,
diff: /**SCHEMA_DIFF*/[
{
"operation": "insert",
"index": 0,
"name": "CardContentWrapper",
"values": {
"itemType": Terrasoft.ViewItemType.CONTAINER,
"wrapClass": ["modal-box-card-content-wrap"],
"items": []
}
},
{
"operation": "insert",
"parentName": "CardContentWrapper",
"propertyName": "items",
"name": "CardContentContainer",
"values": {
"itemType": Terrasoft.ViewItemType.CONTAINER,
"wrapClass": ["modal-box-card-content-container"],
"items": []
}
},
{
"operation": "insert",
"name": "MyContainer",
"propertyName": "items",
"parentName": "CardContentWrapper",
"values": {
"itemType": Terrasoft.ViewItemType.CONTAINER,
"items": []
}
},
{
"operation": "insert",
"name": "HeaderContainer",
"index": 1,
"values": {
"itemType": Terrasoft.ViewItemType.CONTAINER,
"wrapClass": ["header", "modal-box-page-header-container"],
"items": []
}
},
{
"operation": "insert",
"parentName": "HeaderContainer",
"propertyName": "items",
"name": "CloseButtonContainer",
"values": {
"itemType": Terrasoft.ViewItemType.CONTAINER,
"wrapClass": ["close-btn-container"],
"items": []
}
},
{
"operation": "insert",
"parentName": "HeaderContainer",
"propertyName": "items",
"name": "HeaderCaptionContainer",
"values": {
"itemType": Terrasoft.ViewItemType.CONTAINER,
"wrapClass": ["header-name-container"],
"items": []
}
},
{
"operation": "insert",
"parentName": "HeaderCaptionContainer",
"propertyName": "items",
"name": "HeaderCaption",
"values": {
"itemType": Terrasoft.ViewItemType.LABEL,
"caption": "Выберите месяц и год"
}
},
{
"operation": "insert",
"parentName": "MyContainer",
"propertyName": "items",
"name": "MyGridContainer",
"values": {
"itemType": Terrasoft.ViewItemType.GRID_LAYOUT,
"items": []
}
},
{
"operation": "insert",
"parentName": "MyGridContainer",
"name": "OkCloseButton",
"propertyName": "items",
"values": {
"itemType": Terrasoft.ViewItemType.BUTTON,
"style": Terrasoft.controls.ButtonEnums.style.GREEN,
"click": {bindTo: "esqGetNumberMonth"},
"markerValue": "OkCloseButton",
"caption": "Принять",
"layout": { "column": 1, "row": 4, "colSpan": 7 }
}
},
{
"operation": "insert",
"parentName": "MyGridContainer",
"name": "CloseButton",
"propertyName": "items",
"values": {
"itemType": Terrasoft.ViewItemType.BUTTON,
"style": Terrasoft.controls.ButtonEnums.style.BLUE,
"click": {bindTo: "CloseModalPage"},
"markerValue": "CloseButton",
"caption": "Закрыть",
"layout": { "column": 2, "row": 4, "colSpan": 14 }
}
},
{
"operation": "insert",
"name": "OpDate",
"values": {
"layout": {
"colSpan": 14,
"rowSpan": 1,
"column": 1,
"row": 1,
"layoutName": "Header"
},
bindTo: "OpDate",
href: "",
"contentType": Terrasoft.ContentType.ENUM
},
"parentName": "MyGridContainer",
"propertyName": "items",
"index": 11
}
]/**SCHEMA_DIFF*/,
messages: {
"ButtonClose": {
mode: Terrasoft.MessageMode.PTP,
direction: Terrasoft.MessageDirectionType.PUBLISH
},
"DataFromModal": {
mode: Terrasoft.MessageMode.PTP,
direction: Terrasoft.MessageDirectionType.PUBLISH
}
},
methods: {
init: function(callback, scope) {
this.callParent([function() {
Ext.callback(callback, scope);
this.updateSize(400, 300);
}, this]);
},
onCloseButtonClick: function() {
this.sandbox.publish("DataFromModal", null, [this.sandbox.id]);
ModalBox.close();
},
CloseModalPage: function() {
this.sandbox.publish("ButtonClose", null, [this.sandbox.id]);
}
}
};
});
Литвинко Павел,
В Вашем коде у меня была ошибка с ButtonClose. Писал что не подписана карточка на это.
А с кодом по примеру еще пошаманил, но все равно равно ошибки:
ModalBox.show is not a function
и "console" is not defined (а это и в Вашем коде была ошибка такая)
Быстров Сергей,
Ну по первым двум, нужно смотреть, что не так, а console, если ругается на console.log, то можете смело удалить эту строку
Если вам только запросить у пользователя комментарий то зачем рисовать модальные окна? Имхо проще использовать стандартные диалоги и только если их функционал не устраивает рисовать свои:
Terrasoft.showInputBox("Введите свой бесценный комент", function() {}, ["ok"], null, {
name : {
dataValueType: Terrasoft.DataValueType.TEXT,
value: "",
customConfig: {
className: "Terrasoft.MemoEdit",
height: "215px"
}
}
},
{
defaultButton: 0
});
Вот боле полный пример с получением введенного текста
_requestActionComment: function(caption, buttonCaption, maxCommentSize, callback, scope) {
var controls = {
comment: {
dataValueType: Terrasoft.DataValueType.TEXT,
caption: resources.localizableStrings.Comments,
customConfig: {
className: "Terrasoft.MemoEdit",
height: "77px",
maxlength: maxCommentSize
}
}
};
var config = {
defaultButton: 0,
style: {
borderStyle: "ts-messagebox-border-style-blue visa-action",
buttonStyle: "blue"
}
};
var yesButton = {
className: "Terrasoft.Button",
caption: buttonCaption,
returnCode: "yes"
};
Terrasoft.utils.inputBox(caption, function(result, arg) {
if (result === yesButton.returnCode) {
var comment = arg.comment.value;
if (comment && maxCommentSize && comment.length > maxCommentSize) {
comment = comment.substring(0, maxCommentSize);
}
callback.call(scope, comment);
}
}, [yesButton, "cancel"], this, controls, config
);
},
Григорий Чех,
Действительно, это решает мою задачу, но остался вопрос - как создать новый комментарий по введенному тексту?
Немного не понял с callback. Почему нельзя простым this.set?
1) Можно this.set просто пример более глубокий можно передавать callback
2) Как то так значение полей подберите сами
var insert = Ext.create("Terrasoft.InsertQuery", {
rootSchemaName: "SocialMessage"
});
insert.setParameterValue("Message", data.message, Terrasoft.DataValueType.TEXT);
if (data.entityId) {
insert.setParameterValue("EntitySchemaUId", data.entitySchemaId, Terrasoft.DataValueType.GUID);
insert.setParameterValue("EntityId", data.entityId, Terrasoft.DataValueType.GUID);
}
insert.execute(function(result) {
if (result.success) {
//чтото делаем если успешно добавлена запись
});
}
Григорий Чех,
Большое спасибо за помощь. Получилось реализовать все что задумано
coment: function(caption, buttonCaption, maxCommentSize, callback, scope) {
var controls = {
comment: {
dataValueType: Terrasoft.DataValueType.TEXT,
caption: resources.localizableStrings.Comments,
customConfig: {
className: "Terrasoft.MemoEdit",
height: "77px",
maxlength: maxCommentSize
}
}
};
var config = {
defaultButton: 0,
style: {
borderStyle: "ts-messagebox-border-style-blue visa-action",
buttonStyle: "blue"
}
};
Terrasoft.utils.inputBox(caption, function(result, arg) {
if (result === "ok") {
var comment = arg.comment.value;
if (comment != null) {
comment = "<p>" + comment + "</p>";
var insert = Ext.create("Terrasoft.InsertQuery", {
rootSchemaName: "SocialMessage"
});
insert.setParameterValue("Message", comment, Terrasoft.DataValueType.TEXT);
insert.setParameterValue("EntitySchemaUId", "117d32f9-8275-4534-8411-1c66115ce9cd",
Terrasoft.DataValueType.GUID);
insert.setParameterValue("EntityId", this.caseRecordId, Terrasoft.DataValueType.GUID);
window.console.log(insert);
insert.execute(function(result) {
if (result.success) {
window.console.log("dobavili");
}
});
}
}
}, ["ok", "cancel"], this, controls, config);
}