Cохранение на экране без коммита

Здравствуйте ! Есть экран на который я загружаю данные из Excel файла . Следующим способом:

  public void onWorkProcessesTableAdd(Action.ActionPerformedEvent event) {
        FileUploadDialog dialog = (FileUploadDialog) screens.create("fileUploadDialog", OpenMode.DIALOG);
        dialog.addCloseWithCommitListener(() -> {
            UUID fileId = dialog.getFileId();
            File file = fileUploadingAPI.getFile(fileId);
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                byte[] bytes = IOUtils.readFully(fileInputStream, fileInputStream.available());

                List<ContractCustomer> contractCustomers = customersDc.getItems();
                ArrayList<ContractCustomerFacility> actualFacility = new ArrayList<>();

                if (contractCustomers.isEmpty() == true) {
                    notifications.create().withCaption("Добавьте записи в таблицу \"Заказчики\" , " +
                            "указав  связанные объекты").show();
                } else {
                    List<List<ContractCustomerFacility>> contractCustomerFacilities = contractCustomers.stream()
                            .map(cc -> cc.getFacilities()).collect(Collectors.toList());
                    for (List<ContractCustomerFacility> innerList : contractCustomerFacilities) {
                        actualFacility.addAll(innerList);
                    }
                }

                if ((customersDc.getItems().isEmpty() == false) && actualFacility.size() != 0) {

                    ContractHistoryWorkProcessResult candidateRelease = null;

                        candidateRelease = contractHistoryWorkProcessImportService.
                                importFromExcel(bytes, actualFacility, getEditedEntity());

                    ContractHistoryWorkProcessResult result = findDuplicatedItems(candidateRelease);
                    if (result.wp.size() > 0) {
                        dataManager.commit(result.wp.toArray(new ContractHistoryWorkProcess[]{}));
                        contractHistoryDl.load();
                        workProcessesDl.load();

Т.е используя commit. Но выходит так что при нажатии отмена сохранения на этом экране, сущности никуда не исчезают и остаются загруженными. Есть ли обходной путь для подобных ситуаций?

Добрый день!

Чтобы сущности сохранялись в БД только после нажатия OK в экране, нужно не отсылать их сразу в DataManager.commit(), а вносить в DataContext экрана.

Что-то типа такого:

MyEntity mergedEntity = dataContext.merge(myEntity);
collectionDataContainer.getMutableItems().add(mergedEntity);

пытался, но тогда не отображаются загруженные элементы сразу же, там просто пусто. Для отображения приходится переоткрывать экран

Если вы будете добавлять сущности в data container, с которым связаны визуальные компоненты, то эти компоненты будут сразу отображать содержимое контейнера.

Можно ли мержить сразу целый List?

Можно. Только не забудьте что добавлять потом в data container нужно то что вернулось из метода merge().

Я уверен , что контейнер данных верный. НО результат merge ни к чему не приводит

Если коротко , применил ваш способ в отладке просмотрев результат: специально вывел переменную df , чтобы быть уверенным в том, что 1) контейнер связан с таблицей в которую загружаются данные. 2) данные мержатся и добавляются в контейнер, кол-во объектов в нем при выполнении действительно увеличивается. Все эти предположения верны, в пример приведу screen:
image
Однако , данные по завершению загрузки не отображаются на экране все равно, хотя контекст экрана фиксирует изменения , о чем свидетельствует диалоговое окно о сохранении перед закрытием экрана:
image
Descriptor экрана представлен следующим кодом

  <data>
        <instance id="contractHistoryDc" class="com.elgsys.wld.entity.ContractHistory" view="contractHistory-full-view">
            <loader id="contractHistoryDl"/>
            <collection id="customersDc" property="customers">
                <collection id="customerFacilitiesDc" property="facilities">
                    <collection id="workProcessesDc" property="workProcesses"></collection>
                </collection>
            </collection>
            <collection id="documentDc" property="document"/>
            <collection id="payment_schedulesDc" property="payment_schedules"/>
            <collection id="criteriasDs" property="checkListCriterias"/>
        </instance>
        <collection id="workProcessesDc" class="com.elgsys.wld.entity.ContractHistoryWorkProcess">
            <loader id="workProcessesDl">
            <query><![CDATA[select h from wld$ContractHistoryWorkProcess h]]>
                 <condition>
                    <or>
                        <c:jpql>
                            <c:where> (((:currentDateActualCondition >= h.dateStart) and (h.dateFinish > :currentDateActualCondition)) or h.dateFinish is null)</c:where>
                        </c:jpql>
                        <c:jpql>
                            <c:where> ((:currentDateCompletedCondition > h.dateFinish) and (h.dateFinish is not null))</c:where>
                        </c:jpql>
                    </or>
                </condition>
            </query>
            </loader>
        </collection>
        <collection id="days_typesDc" class="com.elgsys.wld.entity.DaysType" view="_minimal">
            <loader id="days_typesDl">
                <query>
                    <![CDATA[select e from wld$DaysType e]]>
                </query>
            </loader>
        </collection>
        <collection id="payment_start_pointsDc" class="com.elgsys.wld.entity.PaymentStartPoint" view="_minimal">
            <loader id="payment_start_pointsDl">
                <query>
                    <![CDATA[select e from wld$PaymentStartPoint e]]>
                </query>
            </loader>
        </collection>
        <collection id="contract_history_typesDc" class="com.elgsys.wld.entity.ContractHistoryType" view="_minimal">
            <loader id="contract_history_typesDl">
                <query>
                    <![CDATA[select e from wld$ContractHistoryType e]]>
                </query>
            </loader>
        </collection>
        <collection id="contractHistoryStatusesDc" class="com.elgsys.wld.entity.ContractStatus" view="_minimal">
            <loader id="contractHistoryStatusesDl">
                <query>
                    <![CDATA[select e from wld$ContractStatus e]]>
                </query>
            </loader>
        </collection>
    </data>
    <dialogMode height="600"
                width="800"/>
    <layout expand="scrollBox" spacing="true">
        <scrollBox id="scrollBox" spacing="true">
            <form id="form" dataContainer="contractHistoryDc">
                <column width="350px">
                    <textField id="nameField" property="name"/>
                    <dateField id="date_addField" property="date_add"/>
                    <dateField id="date_fromField" property="date_from"/>
                    <dateField id="date_toField" property="date_to" required="false"/>
                    <textField id="delay_daysField" property="delay_days"/>
                    <lookupField id="days_typeField" optionsContainer="days_typesDc" property="days_type"/>
                    <lookupField id="payment_start_pointField" optionsContainer="payment_start_pointsDc"
                                 property="payment_start_point"/>
                    <lookupField id="contract_history_typeField" optionsContainer="contract_history_typesDc"
                                 property="contract_history_type"/>
                    <lookupField id="statusField" property="status" optionsContainer="contractHistoryStatusesDc"/>
                </column>
            </form>
            <groupBox id="customersBox" caption="msg://com.elgsys.wld.entity/ContractHistory.customers">
                <table id="customersTable" dataContainer="customersDc" width="100%" height="200px">
                    <actions>
                        <action id="create" type="create">
                            <properties>
                                <property name="screenClass"
                                          value="com.elgsys.wld.web.screens.contractcustomer.ContractCustomerEdit2"/>
                            </properties>
                        </action>
                        <action id="edit" type="edit">
                            <properties>
                                <property name="screenClass"
                                          value="com.elgsys.wld.web.screens.contractcustomer.ContractCustomerEdit2"/>
                            </properties>
                        </action>
                        <action id="remove" type="remove"/>
                    </actions>
                    <columns>
                        <column id="customer"/>
                        <column id="facilities"/>
                    </columns>
                    <buttonsPanel>
                        <button action="customersTable.create"/>
                        <button action="customersTable.edit"/>
                        <button action="customersTable.remove"/>
                    </buttonsPanel>
                </table>
            </groupBox>
            <groupBox spacing="true" id="workProcessesBox" caption="msg://com.elgsys.wld.entity/ContractHistory.work_processes">
                <filter id="filter" dataLoader="workProcessesDl">

                    <properties include=".*"
                                excludeProperties="work_process,
                                firstContractHistory, facility, facility.id"
                               />
                </filter>
                <hbox spacing="true">
                    <checkBox id="actualWorkProcess"
                              caption="msg://actualWorkProcessesС"/>
                    <checkBox id="completedWorkProcess"
                              caption="msg://completedWorkProcessesC"/>
                </hbox>
                <groupTable id="workProcessesTable" dataContainer="workProcessesDc" multiselect="true" width="100%" height="350px">
                    <actions>
                        <action id="create" type="create" caption="msg://quickChWpCreate" icon="PLUS">
                            <properties>
                                <property name="openMode" value="DIALOG"/>
                                <property name="screenClass" value="com.elgsys.wld.web.screens.contracthistoryworkprocess.ContractHistoryWorkProcessEdit2"/>
                            </properties>
                        </action>
                        <action id="remove" type="remove"/>
                        <action id="excel" type="excel"/>
                        <action id="edit" type="edit">
                            <properties>
                                <property name="screenClass" value="com.elgsys.wld.web.screens.contracthistoryworkprocess.ContractHistoryWorkProcessEdit2"/>
                            </properties>
                        </action>
                        <action id="add" enable="true" type="add"/>
                    </actions>
                    <buttonsPanel>
                        <button action="workProcessesTable.create"/>
                        <button action="workProcessesTable.remove"/>
                        <button action="workProcessesTable.edit"/>
                        <button action="workProcessesTable.add" caption="msg://workProcessesC.add"  />
                        <button action="workProcessesTable.excel"/>
                    </buttonsPanel>
                    <columns>
                        <column id="id" caption="msg://idC"/>
                        <column id="customerFacility.contract_customer.contract_history.contract.number" caption="msg://contractC"/>
                        <column id="customerFacility.contract_customer.customer" caption="msg://customerC"/>
                        <column id="customerFacility.facility" caption="msg://facilityC"/>
                        <column id="dateStart" caption="msg://dateStartC"/>
                        <column id="dateFinish" caption="msg://dateFinishC"/>
                        <column id="serviceType.serviceGroup" caption="msg://serviceGroupC"/>
                        <column id="serviceType" caption="msg://serviceTypeC"/>
                        <column id="position.group.name" caption="msg://positionGroupC"/>
                        <column id="position.name"  caption="msg://positionC"/>
                        <column id="scheduleType" caption="msg://shiftTypeC"/>
                        <column id="timeStart" >
                            <formatter class="com.haulmont.cuba.gui.components.formatters.DateFormatter"
                                       format="HH:mm"
                                       useUserTimezone="true"/>
                        </column>
                        <column id="timeFinish">
                            <formatter class="com.haulmont.cuba.gui.components.formatters.DateFormatter"
                                       format="HH:mm"
                                       useUserTimezone="true"/>
                        </column>
                        <column id="breakTime"/>
                        <column id="unit" caption="msg://unitC"/>
                        <column id="customerCost" caption="msg://tariffCustomerC"/>
                        <column id="taxType" caption="msg://taxTypeC"/>
                        <column id="employeeCost" caption="msg://tariffEmployeeC"/>
                        <column id="shiftLength" caption="msg://shiftLengthC"/>
                        <column id="kpi" caption="msg://kpiC"/>
                        <column id="description" caption="msg://descriptionC"/>
                        <column id="requiredDocsString" caption="msg://documentsCodesC"/>
                        <column id="summEmployeeIncludingTax" caption="msg://summEmployeeIncludingTaxC"/>
                    </columns>
                    <rows/>
                </groupTable>
            </groupBox>
            <groupBox id="documentBox" caption="msg://com.elgsys.wld.entity/ContractHistory.document">
                <table id="documentTable" dataContainer="documentDc" width="100%" height="200px">
                    <actions>
                        <action id="add" type="add"/>
                        <action id="exclude" type="exclude"/>
                    </actions>
                    <columns>
                        <column id="name" generator="documentLinkGenerator"/>
                        <column id="createDate"/>
                        <column id="createdBy"/>
                    </columns>
                    <buttonsPanel>
                        <button action="documentTable.add"/>
                        <button action="documentTable.exclude"/>
                    </buttonsPanel>
                </table>
            </groupBox>
            <groupBox id="payment_schedulesBox" caption="msg://com.elgsys.wld.entity/ContractHistory.payment_schedules">
                <table id="payment_schedulesTable" dataContainer="payment_schedulesDc" width="100%" height="200px">
                    <actions>
                        <action id="create" type="create">
                            <properties>
                                <property name="screenClass"
                                          value="com.elgsys.wld.web.screens.paymentschedule.PaymentScheduleEdit2"/>
                            </properties>
                        </action>
                        <action id="edit" type="edit">
                            <properties>
                                <property name="screenClass"
                                          value="com.elgsys.wld.web.screens.paymentschedule.PaymentScheduleEdit2"/>
                            </properties>
                        </action>
                        <action id="remove" type="remove"/>
                    </actions>
                    <columns>
                        <column id="date_start"/>
                        <column id="repeatable"/>
                        <column id="week_num"/>
                        <column id="mon"/>
                        <column id="tue"/>
                        <column id="wed"/>
                        <column id="thu"/>
                        <column id="fri"/>
                        <column id="sat"/>
                        <column id="sun"/>
                    </columns>
                    <buttonsPanel>
                        <button action="payment_schedulesTable.create"/>
                        <button action="payment_schedulesTable.edit"/>
                        <button action="payment_schedulesTable.remove"/>
                    </buttonsPanel>
                </table>
            </groupBox>
            <groupBox id="criteriaBox"
                      caption="msg://com.elgsys.wld.entity/ContractHistory.checkListCriterias">
                <table id="criteriasTable"
                       dataContainer="criteriasDs"
                       height="200px"
                       width="100%">
                    <actions>
                        <action id="create" type="create">
                        <properties>
                            <property name="openMode" value="DIALOG"/>
                            <property name="screenClass" value="com.elgsys.wld.web.screens.contracthistorychecklistcriteria.ContractHistoryCheckListCriteriaEdit"/>
                        </properties>
                        </action>
                        <action id="edit" type="edit">
                            <properties>
                                <property name="openMode" value="DIALOG"/>
                                <property name="screenClass" value="com.elgsys.wld.web.screens.contracthistorychecklistcriteria.ContractHistoryCheckListCriteriaEdit"/>
                            </properties>
                        </action>
                        <action id="remove" type="remove"/>
                    </actions>
                    <columns>
                        <column id="name"/>
                        <column id="percent"/>
                        <column id="dateStart" dateFormat="dd.MM.yyyy"/>
                        <column id="dateEnd" dateFormat="dd.MM.yyyy"/>
                    </columns>
                    <buttonsPanel>
                        <button action="criteriasTable.create"/>
                        <button action="criteriasTable.edit"/>
                        <button action="criteriasTable.remove"/>
                    </buttonsPanel>
                 </table>
            </groupBox>
        </scrollBox>
        <hbox id="editActions" spacing="true">
            <button id="commitAndCloseBtn" action="windowCommitAndClose"/>
            <button id="closeBtn" action="windowClose"/>
        </hbox>
    </layout>
</window>

Необходимые элементы здесь - “workProcessesTable” -таблица для загрузки dataContainer=“workProcessesDc” - контейнер элементов таблицы

Проблема решена.Все дело в том, что я применял Dl.load в загрузчике. Этого делать не нужно.