Displayed data cleared after changing view with getView().setViewName() from an action in OpenXava

105 views Asked by At

I use setViewName() to change the view from an action and it works, but after changing the view all the displayed data goes aways, all the fields are in blank.

This is my action code:

public void execute() throws Exception {
    
    // ...
    // Here there is data displayed in the view
    
    if (article.getManagedBy() == ManagedBy.BATCH) {
        // Batch is defined as @View(name="Batch", members="...") in the entity
        getView().setViewName("Batch"); 
    }
    else if (article.getManagedBy() == ManagedBy.SERIE) {
        // Serie is defined as @View(name="Serie", members="...") in the entity
        getView().setViewName("Serie");
    }
    
    // Now no data is displayed though the view has changed
}

How can I change the view while keeping the displayed data?

1

There are 1 answers

0
javierpaniza On

When you call to View.setViewName() the view data is cleared. This is because OpenXava only loads the displayed data, so if you change to a view that display more data, if we would keep the data, maybe you're going to get some blank field when those fields shoud to have values.

So you're responsible to restore the data after changing the view. If you're sure that Batch and Serie views show exactly the same data (maybe with a different layout), then you can get the data before changing the view and afterwards put it back again. In this way:

// We get the view values before change the view
Map values = getView().getValues();

if (article.getManagedBy() == ManagedBy.BATCH) {
    getView().setViewName("Batch"); 
}
else if (article.getManagedBy() == ManagedBy.SERIE) {
    getView().setViewName("Serie");
}

// Then we put the values back again
getView().setValues(values);

However, if the views diplay different data the above technique does not work well. In that case, you should get the key of the entity, change the view, restore the key into the view and refresh the view from the database. Something like this:

// We get the key before changing the view
Map key = getView().getKeyValues();

if (article.getManagedBy() == ManagedBy.BATCH) {
    getView().setViewName("Batch"); 
}
else if (article.getManagedBy() == ManagedBy.SERIE) {
    getView().setViewName("Serie");
}

// Then we put the key back again
getView().setValues(key);

// And get the data from the database from the key
getView().findObject();