I’m new to cuba so i think that this question is simple for you. I searched the docs and the forum but I have not managed to find a solution yet.
I have an order entity, which has a “number” field (integer).
I created the browse and edit screens for this entity. All work fine.
Now i need to set the value for the field “number” in the edit screen, when the user opens the edit screen.
The value must be the last inserted value + 1.
I managed to override the postInit() function of the edit screen, I can ste a fixed value in the correct field, but i can’t find a way to query the db to get the maximum (or last) inserted number or to pass it from the browse view (that since it has all the records would be easy for me to pick the right one)
How can i solve this little issue?
Is it possible for you to explain me both this techniques?
Perhaps you want to set the “number” value only for newly created entities. Then you should override the initNewItem() method.
In order to load the existing maximum value in a screen controller, you have to use the DataManager.loadValues() method returning the list KeyValueEntity. Alternatively, you could create a middleware service and execute the JPQL query in it using EntityManager. That service could return a simple Integer value.
So the implementation in the controller can be as follows:
package com.company.sample.web.order;
import com.company.sample.entity.Order;
import com.haulmont.cuba.core.entity.KeyValueEntity;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.core.global.ValueLoadContext;
import com.haulmont.cuba.gui.components.AbstractEditor;
import javax.inject.Inject;
import java.util.List;
public class OrderEdit extends AbstractEditor<Order> {
@Inject
private DataManager dataManager;
@Override
protected void initNewItem(Order item) {
item.setNumber(findMaxAndIncrement());
}
private Integer findMaxAndIncrement() {
Integer max = 0;
ValueLoadContext context = ValueLoadContext.create()
.setQuery(ValueLoadContext.createQuery("select max(o.number) from sample$Order o"))
.addProperty("max");
List<KeyValueEntity> list = dataManager.loadValues(context);
if (!list.isEmpty()) {
max = list.get(0).getValue("max");
if (max == null)
max = 0;
}
return ++max;
}
}
Please, can you show me how to use the "middleware " solution? It will suffice a link with a good example (but very simple please, just to grasp the basics )
getItem() returns null in initNewItem() because the current entity is not yet set for the editor - it is just initializing. So you need to set values to the passed argument item, as in my code above:
This instance will later (e.g. in postInit()) be available via getItem().
As for a middleware example - please wait a few days. We are almost done preparing the new “Cookbook” section in the docs, and it will contain the “Organizing Business Logic” section among others, with demos. It will certainly answer your question.