0

Need some help selecting the PrimeFaces p:dataTable 1st row on page load, here's my code so far:

<p:dataTable id="dtbList" value="#{Controller.items}" var="item" widgetVar="dataTableList" lazy="true" 
selection="#{Controller.selectedValue}" rowKey="#{item.key}" 
scrollable="true" scrollHeight="133">

<p:ajax event="rowSelectRadio" listener="#{Controller.handleSelectList}" update="dtbList" 
oncomplete="resetScroll();"/>
...
...
...
</p:dataTable>

I've tried using ajax event to no avail

<p:ajax event="page" onsuccess="PF('dataTableList').selectRow(0);"/>

Wondering where I did wrong.

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
kuro
  • 57
  • 5

2 Answers2

0

If you know the rowKey (the id) of your first row try to add the property dynamic="true" in your dataTable component like this :

<p:dataTable id="dtbList"
value="#{Controller.items}" var="item"
widgetVar="dataTableList" lazy="true"
selection="#{Controller.selectedValue}"
rowKey="#{item.key}"
scrollable="true" scrollHeight="133"
dynamic="true">
...
...
...
</p:dataTable>

And, in your bean(Controller) create a method annotated by @PostConstruct, in witch you can select the best element. Like this:

@PostConstruct
public void init() {
    this.selectedValue = new SelectedValueEntityType();
    this.selectedValue.setKey('yourKey');
}
  • As chances are high that a datasource is used to get items, and that there are many of them. Besides the fact that hardcoding an item is ugly, chances are that the item is not the first row (anymore) or not present at all. – Jasper de Vries Dec 21 '22 at 12:39
0

The page event is triggered on pagination, so not on the initial load.

You might want to make the controller a property of the LazyDataModel you've implemented (assuming you did; if you are using the JpaLazyDataModel, extend it). Now you can access the controller from the load method. You can now simply check if no selection was made and set the first item that was fetched in the load method as the selected item of the controller.

See also: https://primefaces.github.io/primefaces/12_0_0/#/components/datatable

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102