Listening to Fragment Events in Host Screen

Hello we have a Host screen class where we are creating our fragments.
We put the fragments in a HashMap and then we are loading a comboBox with the HashMap.
We use the comboBox to switch between the fragments. What we would like to achieve is subscribing for an event from the Host screen,
so we can visualize a warning on it. The event should be triggered from any of the fragments related to the Host screen.
What would be the best way to achieve this?

We have tried followingListening to Fragment Events in Host Screen, but we are getting the below error upon opening the HostScreen.
java.lang.UnsupportedOperationException: Unsupported @Subscribe target CONTROLLER. It is not a Fragment. at io.jmix.ui.sys.UiControllerDependencyInjector.initSubscribeListeners(UiControllerDependencyInjector.java:317)

Kind regards,
Dimitar

Hi,

What id did you put to the annotation?

@Subscribe(id = "addressFragment", target = Target.CONTROLLER)

Is it an id of the Fragment?

Yes we’ve tried using by following the pattern below:
@Subscribe(id = “addressFragment”, target = Target.CONTROLLER)

Kind regards,
Dimitar

I’ve just tested it on the new project and everything works like it is described in the documentation.

See BlankScreen in my project: fragment-event.zip (85.2 KB)

If you can reproduce your issue on a small test project please attach it here. It’ll be easier to understand what’s wrong.

Hello,
I reproduced the issue by changing the way fragments are loaded into the host screen (from declarative to programmatic) → Using Screen Fragments :: Jmix Documentation

fragment-event.zip (316.3 KB)

In our application besides that we are loading the fragments programmatically, we are using Map to load the fragments and ComboBox for switching between them.

Kind regards,
Dimitar

If you add fragments programmatically then the following listener can’t work because when the screen is initialized there is no fragment with the newFragment id on the screen:

@Subscribe(id = "newFragment", target = Target.CONTROLLER)

Instead of declaring the listener using the method with the @Subscribe annotation you may explicitly add listener to the fragment when the fragment is created and added to the screen:

    @Subscribe
    private void onInit(InitEvent event) {
        NewFragment fragment = fragments.create(this, NewFragment.class);
        fragmentBox.add(fragment.getFragment());
        fragment.addChangeListener(fragmentBtnClickEvent -> {
            screenField.setValue(fragmentBtnClickEvent.getText());
            notifications.create()
                    .withCaption(fragmentBtnClickEvent.getText())
                    .show();
        });
    }