Reputation: 1116
I have a datatable which has columns defined in my entity. I also added another column named total
in index.xhtml:
...
<p:column headerText="total">
<h:outputText value="#{bean.total}" />
</p:column>
...
This column calculates and returns the sum of columns in each row. Everything works fine except when I want to sort/filter by columns, the total
column remains untouched.
I guess I should add the total
field in my entity too, but it doesn't seem practical.
Does primefaces has a better and more straight solution for such situations?
Upvotes: 4
Views: 2003
Reputation: 1539
Since you want the entity class to remain immutable, I can think of two solutions for the matter:
1) Create a subclass of your entity, but do not declare it as an entity. You can also create a wrapper class receiving Entity
as a constructor parameter, and directly manipulating the data on the original object via getters and setters. Subclassing has the advantage of inheriting the public methods already, but the disadvantage of having to care for the data.
Check this answer on why not to subclass an entity as an entity and the persistance issues.
public class EntitySubclass extends Entity {
private Entity parent;
public EntitySubclass(Entity parent) {
this.parent = parent;
// set all data from parent to this entity.
}
// fetch the parent object for persistance.
public Entity getParent() {
// set all data from this to parent.
}
public int getTotal() {
int iDidMathOnEntityData = 0;
// do math
return iDidMathOnEntityData;
}
}
jsf:
<p:column headerText="total">
<h:outputText value="#{subClass.total}" />
</p:column>
2) Use the rowIndexVar
(https://stackoverflow.com/a/5704087/1532705) and call a method on the Managed Bean passing the rowIndexVar
as parameter. Then fetch the corresponding entity and do the math. Requires EL 2.2.
<p:column headerText="total">
<h:outputText value="#{bean.total(rowIndexVar)}" />
</p:column>
managed bean:
public int total(int rowIndexVar) {
int iDidMathOnEntityData = 0;
Entity e = getEntityByIndex(rowIndexVar);
// do some math
return iDidMathOnEntityData;
}
3) if someone with the same issue has no problem with editting the entity, you can add the getTotal()
method as @Transient
:
@Transient
public int getTotal() {
int iDidMathOnEntityData = 0;
// do math
return iDidMathOnEntityData;
}
Upvotes: 5