Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PrimeFaces DataTable CellEdit get entity/object

I have a datatable which displays various entities based on a List<>. When I select a cell for editing I want to be able to also get the entity somehow in order to update it. Of course there is event.getRowIndex, which I can then use with the List<>, but that is not always convenient. Is there perhaps another way to get the entity from CellEditEvent?

like image 827
ChrisGeo Avatar asked Sep 04 '13 10:09

ChrisGeo


2 Answers

One way would be to programmatically EL-evaluate the current <p:dataTable var>.

Given a

<p:dataTable value="#{bean.entities}" var="entity">

you could get it as follows

public void onCellEdit(CellEditEvent event) {
    FacesContext context = FacesContext.getCurrentInstance();
    Entity entity = context.getApplication().evaluateExpressionGet(context, "#{entity}", Entity.class);
    // ...
}

Another way, if you're not interested in the CellEditEvent argument, would be to override the CellEditEvent argument altogether by passing the currently iterated entity as argument instead:

<p:ajax event="cellEdit" listener="#{bean.onCellEdit(entity)}" />

with

public void onCellEdit(Entity entity) {
    // ...
}

Please note that you cannot keep the CellEditEvent and pass additional arguments. This answer would otherwise obviously have been given.

like image 169
BalusC Avatar answered Nov 09 '22 17:11

BalusC


I have been struggling with this problem two and I didn't like depending the var name so I found this solution:

public void onCellEdit(CellEditEvent event) {  
    Entity entity =(Entity)((DataTable)event.getComponent()).getRowData();
}

note that the entity is updated can be merged directly into the DB, also you can still get the old value. PS: thank you @BalusC for everything :)

like image 33
user1928596 Avatar answered Nov 09 '22 16:11

user1928596