0

How do I execute code when the user clicks a cell in a data table? Similarly to listener and actionListener on a p:commandButton.

For example

<p:commandButton oncomplete="PF('editProductDialog').show()" 
   actionListener="#{bean.doStuffToGetASelectOneMenuReadyforTheEditProductDialog()}" />
public void doStuffToGetDialogReady() {
   //query databases to get select item list
}

The database is only queried when/if the user clicks the commandButton

But for p:dataTable inline cell editing how to I call code that would query database to get select items only when they click the data table cell to make an edit?

<p:cellEditor>
    <f:facet name="output"/>
    <f:facet name="input">
        <p:selectOneMenu>
            <f:selectItems value="#{bean.someListSpecificToThisUser}" />
        </p:selectOneMenu>
    </f:facet>
</p:cellEditor>

I've been populating the someListSpecificToThisUser selectItems list in the @PostConstruct init() method

@PostConstruct
public void init() {
     //code specific to the page and datatable
     someListSpecificToThisUser = service.queryValuesForUser(user);
}

but if the user never clicks the cell to edit the selectOneMenu value then I hit the database and stored the list in memory for no reason. Or should I not worry about the overhead?

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
jeff
  • 3,618
  • 9
  • 48
  • 101

1 Answers1

2

In case of cell editing of a p:dataTable there are a few events you can use:

Event Fired
cellEdit When a cell is edited.
cellEditCancel When a cell edit is cancelled e.g. with escape key
cellEditInit When a cell edit begins.

All taking a org.primefaces.event.CellEditEvent as the listener parameter.

You could use the cellEditInit method to populate the list when it is still null. Downside is that this requires an Ajax call on each edit init.

An other option you have is to store the list in a SessionScoped user bean, which will cost you some memory.

The option to pick depends on the size of the list, how much time it takes to fetch the list and how many edits you expect. If you don't expect much edits, use an Ajax listener to populate the list. If the list is long and takes some time to load, I would switch to a p:autoComplete field.

See also:

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
  • Nice answer however, the cellEditInit event is called regardless of which cell is edited and I have the cellEdit on a number of columns. I'll stick with db query and loading in the view init/postconstruct. It's been working fine that way for a while, I was looking at was to improve app efficiency and overhead. – jeff Apr 19 '21 at 14:59
  • The `CellEditEvent` contains both the row index and the `UIColumn`, see https://github.com/primefaces/primefaces/blob/master/src/main/java/org/primefaces/event/CellEditEvent.java – Jasper de Vries Apr 19 '21 at 15:06