How to declare a function in a "detail1.java" from "detail2.java" in Jmix2.0

How to declare a function in a “detail1.java” from “detail2.java” in Jmix2.0?

Hi,

Could you please describe in more detail what you want to achieve?

Regards,
Gleb

For example, I create a function in “detail2.java” but I also want to use the function in “detail1.java”. So how to declare a function in a “detail1.java” from “detail2.java” in Jmix2.0?

I still don’t get the task. Do you need to call a method when opening a view programmatically or is it some kind of utility method suitable for any view?

FuelDetails2DetailView.java:

private void loadFuelDetails() {
// TruckDriver selectedDriver = driverNameListField.getValue();
VehicleMasterList selectedMasterList = masterListField.getValue();
String detailDate = detailDateField.getValue();
// String timeValue = timeField.getValue(); // Assuming time is in HH:mm:ss format

    try {
        if (selectedMasterList != null && detailDate != null) {

// if (selectedDriver != null && selectedMasterList != null) {

// LocalTime time = LocalTime.parse(timeValue); // Assuming time is in HH:mm:ss format

            List<FuelDetails2> fuelDetailsList = dataManager.load(FuelDetails2.class)
                    .query("select e from FuelDetails2 e " +
                            "where e.detailDate = :detailDate " +
                            "and e.masterList = :masterList " +
                            "order by e.time desc")//"and e.detailDate = :detailDate ")
                    .parameter("detailDate", detailDate)
                    .parameter("masterList", selectedMasterList)//                        .parameter("detailDate", detailDate)
                    .list();

            // Adjust the time by adding 8 hours
            fuelDetailsList.forEach(detail -> {
                if (detail.getTime() != null) {
                    LocalTime adjustedTime = detail.getTime().plusHours(7).plusMinutes(30);
                    detail.setTime(adjustedTime);
                }
            });


            emptyDataGridCollection.setItems(fuelDetailsList);

            // Calculate the total fuel price
            Double totalFuelPrice = calculateTotalFuelPrice();

            // Set the total fuel price in the text field
            totalFuelPriceField.setValue(totalFuelPrice != null ? totalFuelPrice.toString() : "0.0");

            // Calculate the total fuel price
            Double totalFuelQuantity = updateTotalFuelQuantity();

            // Set the total fuel price in the text field
            quantityField.setValue(totalFuelQuantity != null ? totalFuelQuantity.toString() : "0.0");

        } else {
            emptyDataGridCollection.setItems(Collections.emptyList());
        }
    } catch (Exception e) {
        // Handle the exception or log it for debugging
        e.printStackTrace();
        notifications.show("An error occurred while loading fuel details.");
    }
}

DialogView.java:

private void validateAndSave(final ClickEvent event) {
if (validateForm()) {
if (isNewOdometerGreater()) {
Dialog confirmationDialog = new Dialog();
confirmationDialog.addClassName(“confirmation-dialog2”);

            confirmationDialog.setCloseOnEsc(false);
            confirmationDialog.setCloseOnOutsideClick(false);

            Label messageTitle = new Label("Publish Fuel Data");
            messageTitle.addClassName("message-title2"); // Add the CSS class

            // Create an HTML <hr> element
            HtmlComponent hr = new HtmlComponent("hr");
            hr.addClassName("divider2"); // Add a CSS class for styling

            Label messageLabel = new Label("Your data is about to be published. Click confirm to proceed.");
            messageLabel.addClassName("message-label2");

            Button confirmButton = new Button("Confirm");
            confirmButton.addClassName("confirm-button2");

            Button cancelButton = new Button("Cancel");
            cancelButton.addClassName("cancel-button2");

            confirmationDialog.add(messageLabel, confirmButton, cancelButton);
            confirmationDialog.open();

            // Create a layout for buttons
            HorizontalLayout buttonLayout = new HorizontalLayout(confirmButton, cancelButton);
            buttonLayout.addClassName("button-layout2");
            buttonLayout.setSpacing(true);

            // Create a layout for the dialog content
            VerticalLayout dialogLayout = new VerticalLayout(messageTitle, hr, messageLabel, buttonLayout);
            dialogLayout.setAlignItems(FlexComponent.Alignment.CENTER);
            dialogLayout.setSpacing(true);

            confirmButton.addClickListener(e -> {
                // Save the edited entity using the DataLoader
                saveData();
                confirmationDialog.close();
            });

            cancelButton.addClickListener(e -> {
                confirmationDialog.close();
            });

            confirmationDialog.add(dialogLayout);
            confirmationDialog.open();
        } else {
            // Display an error message or handle the validation failure
            Notification.show("New Odometer must be greater than Last Odometer. " +
                            "newOdometerValue: " + newodometerField.getValue() +
                            ", lastOdometerValue: " + lastodometerField.getValue(),
                    3000, Notification.Position.TOP_CENTER);
        }
    } else {
        // Form is invalid, display an error message or take appropriate action
        notifications.show("Please fill in all required fields and correct any validation errors.");
    }
}

How to declare the function (" loadFuelDetails() “) of “FuelDetails2DetailView.java” into “confirmButton.addClickListener” of the function (” validateAndSave(final ClickEvent event) ") of “DialogView.java”?

I still don’t get you need to call a method from one view in another. Do you need to call a method when opening a view programmatically or is it some kind of utility method suitable for any view?

Hi Gleb, I apologize for not explaining it well enough as I not fluent in explaining it, I have 2 view, lets call it view1 and view2, I want to use a function in view1 in which I can call it from view2. Probably from your suggestions, I may need some kind of utility method suitable for any view. Once again, I apologize as I unable to explain it very clearly.

One view can interact with another view only if the second view is opened as a Dialog. Depending on your task, you can call a method, e.g. to pass parameters to the opened view. TO do this invoke the build() terminal method, set parameters to the view, then open the window:

@Autowired
private DialogWindows dialogWindows;

private void openViewWithParams(String username) {
    DialogWindow<MyOnboardingView> window =
            dialogWindows.view(this, MyOnboardingView.class).build();
    window.getView().setUsername(username);
    window.open();
}

Alternatively, to get a result from the opened view after it is closed, add AfterCloseEvent listener to the dialog window:

@Autowired
private DialogWindows dialogWindows;

private void openViewWithParamsAndResults(String username) {
    DialogWindow<MyOnboardingView> window =
            dialogWindows.view(this, MyOnboardingView.class).build();
    window.getView().setUsername(username);
    window.addAfterCloseListener(afterCloseEvent -> {
        if (afterCloseEvent.closedWith(StandardOutcome.SAVE)) {
            // ...
        }
    });
    window.open();
}

Take a look at the doc for more details: Opening Views :: Jmix Documentation

For reusable logic in several views, you can create a spring bean using studio:

Screenshot 2023-10-18 at 12.11.00

Gleb

@Autowired
private DialogWindows dialogWindows;

private void openViewWithParamsAndResults(String username) {
DialogWindow window =
dialogWindows.view(this, MyOnboardingView.class).build();
window.getView().setUsername(username);
window.addAfterCloseListener(afterCloseEvent → {
if (afterCloseEvent.closedWith(StandardOutcome.SAVE)) {
// …
}
});
window.open();
}

Can I use a function in Dialog view which the fucntion is declared or created in another view?

if you pass it as an input parameter to the opened view.

Can you show an example?