Using addPropertyChangeListener

Hi!

I would like to Use a getItem().addPropertyChangeListener This is the Code.


public void init(Map<String, Object> params) {
        lineasDs.addCollectionChangeListener(e -> calculartotal());
        //lineasDs.addItemPropertyChangeListener(e -> calculartotallinea());
        lineasDs.addItemPropertyChangeListener(e -> {
            if (e.getProperty().equals("articulo")){
                if ((lineasDs.getItem() != null) && (lineasDs.getItem().getArticulo() !=null))
                lineasDs.getItem().setDescripcion(lineasDs.getItem().getArticulo().getNombre());
                lineasDs.getItem().setTipoIva(lineasDs.getItem().getArticulo().getIva());
                lineasDs.getItem().setPorcentajeIva(lineasDs.getItem().getArticulo().getIva().getIva());
                calculartotallinea();
            }
            calculartotallinea();
        });
        getItem().addPropertyChangeListener(e -> {
            if (e.getProperty().equals("clientes") && getItem().getClientes() != null) {
                getItem().setVendedor(getItem().getClientes().getVendedor());
            }
        });
    }

When i enter on Screen i Get a null Value for this line:

    getItem().addPropertyChangeListener(e -> {

It’s not correctly set the addPropertyChangeListener ?

Hi Ivan,
The getItem() method should not be used in init(), because the edited instance is not set to the main datasource yet. Use postInit() for adding your listener to the entity. This is explained here: https://doc.cuba-platform.com/manual-6.2/abstractEditor.html

Important notice: Do not add listeners directly to entity because listeners for events fired by entity are stored in weak references, so they will be removed from memory if no one holds strong references to them.

You should never use listeners on entity, but instead I recommend to use listeners on datasource that contains this entity.

1 Like

Hi i’ve added code to PostInit, but not affect the listeners, has no changes, and not breack when i make any change:


@Override
    protected void postInit() {
         getItem().addPropertyChangeListener(e -> {
           if (e.getProperty().equals("clientes") && getItem().getClientes() != null) {
                getItem().setVendedor(getItem().getClientes().getVendedor());
            }
        });
    }

Solved, i’ve added:


 @Named("fieldGroup.clientes")
    private PickerField clientes;

@Override
    protected void postInit() {
        clientes.addValueChangeListener(e -> {
            if (e.getValue() !=null) {
                showNotification("Cliente seleccionado", NotificationType.HUMANIZED);
                getItem().setVendedor(getItem().getClientes().getVendedor());
            }
        });
    }