Primefaces Datalist Pagination - jsf-2

I'm using a datalist with Ajax pagination and the first page loads fine, showing 5 results. It knows I've got 3 pages worth of results, but when I click through to the second/third pages, I get an empty list.
My model extends LazyDataModel and the first time my page loads, I can set a breakpoint on the load() method and I can see it's asking for results 1-5 which is great. But clicking on 'page 2' doesn't result in another call to the load method (although it does result in about 3 calls to my lazyDataModel field itself (just not the load method inside it).
New to this and despite reading a lot and trying out various things, I can't understand quite how it should work. The showcase example doesn't seem quite 'complete' to me.
Here's the most relevant bits of my code (I think). Sorry about the formatting:
#PostConstruct
public void LoadData() {
lazyModel = new LazyDataModel<MessageboardThread>() {
#Override
public List<MessageboardThread> load(int first, int pageSize, String sortField, SortOrder so, Map<String, String> map) {
List<MessageboardThread> result = new ArrayList<MessageboardThread>();
try {
result = mbDao.findAll(pageSize, first);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
};
getLazyModel().setRowCount(mbDao.count());
getLazyModel().setPageSize(pageSize);
}
This method DOES get executed every time I click on next/prev page
/**
* #return the lazyModel
*/
public LazyDataModel getLazyModel() {
return lazyModel;
}
And this is my xhtml file
<p:dataList value="#{messageboardBean.lazyModel}" var="thread" id="threads"
paginator="true" rows="5" effectSpeed="fast"
paginatorTemplate="{PreviousPageLink} {CurrentPageReport} {NextPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15" type="none"
paginatorPosition="bottom">
<f:facet name="header">
Conversations
</f:facet>
<p:column>
<h:outputText value="#{thread.title}" style="margin-left:10px" />
<br />
</p:column>
</p:dataList>
I'm stumped so really grateful for any help
PS I put a #PostContruct annotation there because it seemed to be a good place to do the setup but it could be wrong, I haven't seen it on any other examples, but then I couldn't get any other examples to work either.

Solved it. I forgot to wrap the dataList attribute in an h:form tag. It works fine now.

Related

PrimeFaces inputText enable/disable

I have two radio buttons on JSF2/PrimeFaces page, which I need to enable/disable an inputText field depending on the choice.
<h:form prependId="false">
<p:panelGrid id="notif">
<p:row id="notif1">
<p:column>
<h:outputText value="label" />
</p:column>
<p:column>
<p:selectOneRadio id="radiobuttons" value="#{state.radioStatus}" layout="pageDirection">
<f:selectItem itemLabel="enable" itemValue="enable" />
<f:selectItem itemLabel="disable" itemValue="disable" />
<p:ajax update="date" />
</p:selectOneRadio>
</p:column>
<p:column>
<p:inputText id="date" value="#{state.infoDate}" disabled="#{!state.checkStatus}" >
</p:inputText>
<p:inputText id="test" value="#{state.infoDateTest}">
</p:inputText>
</p:column>
</p:row>
</p:panelGrid>
</h:form>
Also this all is inside a tab, but there is no nested forms when checked the generated html. The fields seem to get the id of the tab, but they seem to be correct like this (Did not work when tried to use id notation 'tabView:date' for the ajax.)
The problem is that when entering the page, the 'actual' text field is disabled by default and should be enabled when the radio button is set to enable it. When the radio button status is updated, I can see the event is registered on the server side and the inputText field gets "visually" enabled (by default it is disabled as supposed to). However the field is not "focusable" after enabling it, so can't write to it.
The more bizarre it gets when I added the 'test' inputText field, which does not get it self enabled/disabled regarding to radio buttons. On a fresh page load you can write to it, but after changing the radio button status, it is not writable anymore (the text that was entered prior to ajax call, will remain, but is not editable).
However the radio buttons continue to work and will fire events on the server side.
Could someone point out what I may be doing incorrectly, or could this be a bug with PrimeFaces?
// Update
Like said, the managed bean works as supposed to, so I don't see any problems there, but here is the code (simplified and renamed for readability as the relevant parts are taken from a bigger context).
#ManagedBean(name = "state")
#SessionScoped
public class ExampleBean implements Serializable {
private static final String disable = "disable";
private static final String enable = "enable";
private String text;
private List<TestRow> rows = null;
private TestRow row = null;
private String radioStatus = "enable";
private String infoDate = "";
private String infoDateTest = "";
#PostConstruct
public void initEmpty() {
}
public String getRadioStatus() {
return this.radioStatus;
}
public void setRadioStatus(String radioStatus) {
this.radioStatus = radioStatus;
}
public String getInfoDate() {
return infoDate;
}
public void setInfoDate(String infoDate) {
this.infoDate = infoDate;
}
public String getInfoDateTest() {
return infoDateTest;
}
public void setInfoDateTest(String infoDateTest) {
this.infoDateTest = infoDateTest;
}
public boolean isCheckStatus() {
return this.radioStatus.equalsIgnoreCase(enable) ? true : false;
}
}
Unfortunately I was not able to figure out what is causing the actual problem. The basic thing seems to be that the inherited javascript (primefaces) is not working properly on this page (maybe because of some other js inherited). Finally I just made it a custom enable/disable js-function:
js.toggleDisableStatus = function(elementId) {
// Can't use jQuery $("#xx:yy"), the syntax is not accepted by jquery but
// used by JSF/PrimeFaces
var element = document.getElementById(elementId);
var attrValue = element.getAttribute('disabled');
if (attrValue === undefined || attrValue == null) {
element.disabled = true;
element.style.background = "#dddddd";
} else {
element.removeAttribute('disabled');
element.style.background = "";
}
};
This may be flawed but works for now. The radio buttons are selected by the persisted status (loaded in state) and the enable/disable state for the input-field is also set when initially loading the page. Generally I think this should work for this particular case.

PrimeFaces lazydatamodel load method not called

I happen not to understand why my load method is not called in a lazydatamodel of my primefaces table. My xhtml page goes like this
<h:form id="myForm">
<p:dataTable value="#{myBean.configDataModel}"
id="configTable" var="config" paginator="true" rows="10"
selectionMode="single"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,20">
.
.
</h:form>
My Bean code goes like this and put up system.out.println statements but I notice it isn't called.
public class MyBean{
// private List<MyBean> configList;
private LazyDataModel<MyBean> configDataModel;
#SuppressWarnings("serial")
public LazyDataModel<MyBean> getConfigDataModel() {
if (configDataModel == null) {
configDataModel = new LazyDataModel<MyBean>() {
#Override
public List<MyBean> load(int arg0, int arg1, String arg2,
SortOrder arg3, Map<String, String> arg4) {
System.out.println("Here!!!!!");
return null;
}
};
}
return configDataModel;
}
public void setConfigDataModel(LazyDataModel<MyBean> configDataModel) {
this.configDataModel = configDataModel;
}
}
What could be the cause?
Since PrimeFaces 3.3, you'd need to explicitly set the lazy attribute of the repeating component to true in order to enable the support for LazyDataModel.
<p:dataTable ... lazy="true">
See also:
PrimeFaces showcase - DataTable - Lazy Loading
If you are IE, be sure to check which so-called "compatibility mode" it is quirking in. I have had very annoying problems with lazy datatable failing to call its load method after I typed text into the filter field. After much wasted time, I eventually realized that the browser was running in default mode 7. Datatable lazy load works for modes 8, 9, 10
If your lazy datatable is in a dialog, then be sure to place the dialog within the form, otherwise, typing values into a filter field will not submit to the load method.

Handling view parameters in JSF after post

I have a few pages that needs a userId to work, thus the following code:
userpage.xhtml
<!-- xmlns etc. omitted -->
<html>
<f:metadata>
<f:viewParam name="userId" value="#{userPageController.userId}"/>
</f:metadata>
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h:commandButton action="#{userPageController.doAction}" value="post"/>
</h:form>
</h:body>
</f:view>
userPageController.java
#Named
#ViewScoped
public class userPageControllerimplements Serializable {
private static final long serialVersionUID = 1L;
#Inject protected SessionController sessionController;
#Inject private SecurityContext securityContext;
#Inject protected UserDAO userDAO;
protected User user;
protected Long userId;
public UserPage() {
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
if(!FacesContext.getCurrentInstance().isPostback()){
User u = userDAO.find(userId);
this.userId = userId;
this.user = u;
}
}
public void doAction(){
}
}
However, after doAction is called, the view parameter in the url disappears. The bean still works due to its viewscoped nature, but it ruins my attempts of future navigation. When i search around, I get the impression that the view parameter should remain after a post thus reading userpage.jsf?userId=123, but this is not the case. What is really the intended behaviour?
Related to this, I've tried to implement automatic adding of view parameters when navigating to another page where I want to keep the userId. It seems to work for others, but for me, the userId in the ViewRoot is always null. Code below used to retrieve the viewparameter (i know i could use my temporarily stored userId in the bean for navigation, but this solution would be much fancier):
String name = "userId";
FacesContext ctx = FacesContext.getCurrentInstance();
ViewDeclarationLanguage vdl = ctx.getApplication().getViewHandler().getViewDeclarationLanguage(ctx, viewId);
ViewMetadata viewMetadata = vdl.getViewMetadata(ctx, viewId);
UIViewRoot viewRoot = viewMetadata.createMetadataView(ctx);
UIComponent metadataFacet = viewRoot.getFacet(UIViewRoot.METADATA_FACET_NAME);
// Looking for a view parameter with the specified name
UIViewParameter viewParam = null;
for (UIComponent child : metadataFacet.getChildren()) {
if (child instanceof UIViewParameter) {
UIViewParameter tempViewParam = (UIViewParameter) child;
if (name.equals(tempViewParam.getName())) {
viewParam = tempViewParam;
break;
}
}
}
if (viewParam == null) {
throw new FacesException("Unknown parameter: '" + name + "' for view: " + viewId);
}
// Getting the value
String value = viewParam.getStringValue(ctx); // This seems to ALWAYS be null.
One last thought is that the setter methods still seem to work, setUserId is called with the correct value on post.
Have I completly missunderstood how view parameters work, or is there some kind of bug here? I think my use case should be extremly common and have basic support in the framework.
When i search around, I get the impression that the view parameter should remain after a post thus reading userpage.jsf?userId=123, but this is not the case. What is really the intended behaviour?
This behaviour is correct. The <h:form> generates a HTML <form> element with an action URL without any view parameters. The POST request just submits to exactly that URL. If you intend to keep the view parameters in the URL, then there are basically 3 ways:
Bring in some ajax magic.
<h:commandButton action="#{userPageController.doAction}" value="post">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
This way the initially requested page and thus also the request URL in browser's address bar remains the same all the time.
If applicable (e.g. for page-to-page navigation), make it a GET request and use includeViewParams=true. You can use <h:link> and <h:button> for this:
<h:button outcome="nextview?includeViewParams=true" value="post" />
However, this has an EL security exploit in Mojarra versions older than 2.1.6. Make sure that you're using Mojarra 2.1.6 or newer. See also issue 2247.
Control the generation of action URL of <h:form> yourself. Provide a custom ViewHandler (just extend ViewHandlerWrapper) wherein you do the job in getActionURL().
public String getActionURL(FacesContext context, String viewId) {
String originalActionURL = super.getActionURL(context, viewId);
String newActionURL = includeViewParamsIfNecessary(context, originalActionURL);
return newActionURL;
}
To get it to run, register it in faces-config.xml as follows:
<application>
<view-handler>com.example.YourCustomViewHandler</view-handler>
</application>
This is also what OmniFaces <o:form> is doing. It supports an additional includeViewParams attribute which includes all view parameters in the form's action URL:
<o:form includeViewParams="true">
Update: obtaining the view parameters of the current view programmatically (which is basically your 2nd question) should be done as follows:
Collection<UIViewParameter> viewParams = ViewMetadata.getViewParameters(FacesContext.getCurrentInstance().getViewRoot());
for (UIViewParameter viewParam : viewParams) {
String name = viewParam.getName();
Object value = viewParam.getValue();
// ...
}
Am I right that for solution 1 <f:ajax execute="#form" render="#form" /> to work one would also have to include something like
<f:param name="userId" value="#{userPageController.userId}"/>
inside the <h:commandButton>?
Like it is described in https://stackoverflow.com/a/14026995/811046

Implement LazyDataModel in p:dataTable

I'm trying to implement a table with lazy loading. I think I got all steps from demo page and documentation but I always get a "No records found" message. I think I've reduced code to minimun expression, at least there should be one record :
Tables page:
<h:form id="listaEmpresas">
<p:dataTable id="tablaEmpresas" value="#{empresasTableMB.lazyDataModel}" var="empresa">
<p:column>
<f:facet name="header">
<h:outputText value="#{msgs.empresa_tabla_nombre}"/>
</f:facet>
<h:outputText value="#{empresa.nombre} "/>
</p:column>
</p:dataTable>
</h:form>
LazyDataModel:
#Override
public List<Empresa> load(int first, int pageSize, String sortField, SortOrder so, Map<String, String> filters) {
List<Empresa> listaEmpresas = new ArrayList();
Empresa e = new Empresa();
e.setNombre("Company");
listaEmpresas.add(e);
this.setRowCount(1);
return listaEmpresas;
}
#Override
public void setRowIndex(int rowIndex) {
if (rowIndex == -1 || getPageSize() == 0) {
super.setRowIndex(-1);
}
else
super.setRowIndex(rowIndex % getPageSize());
}
I must override setRowIndex or I get an exception "java.lang.ArithmeticException: / by zero". I'm using primefaces-3.1-SNAPSHOT, jsf 2.0.3, and tomcat 6.0. Please help. What I´m missing?
Add lazy=true in your dataTable.
After adding this datatable is able to call your load() method.
you need to add field private int rowCount;
and then in your load(...) method set value of number of record in your list to this field (rowCount).
without this thing <p:dataTable ...> will gain "No record found" and also if you don't specify rows ="10" (for example) attribute it will not render rows!
You need to implement LazyDataModel#getRowKey and LazyDataModel#getRowData as well.
Suppose that you have something like:
class Empresa {
private long id;
private String nombre;
// getters and setters...
}
Then:
getRowKey returns the id for an Empresa object
getRowData gets an Empresa object by id
class MyLazyDataModel {
// stuff you already have comes here...
public Empresa getRowData(String rowKey) {
return empresaRepository.getEmpresaById(Long.valueOf(rowKey));
}
public Object getRowKey(Empresa empresa) {
return empresa.getId();
}
}
This behavior is described in https://code.google.com/p/primefaces/issues/detail?id=1544 and apparently you can avoid it by explicitly calling lazyDataModel.setPageSize();
There is a related post here:
Primefaces DataTable + JPA / Hibernate Pagination
you are not calling the load method.first call the load method before the prime face data table declaration.

commandbutton not executing action if other attributes are bind to managed bean

i'm really new to jsf.
I need to enable,disable, render or not render some buttons on a page depending on the logged user privileges. The page is bound to a request scoped managed bean , i bind the rendered or disabled attribute of the commandbutton to a "visible" property of the managed bean, and an actionlistener to a managedbean method which has the only purpose to navigate to another page.
If i bind one of the above properties to the visibile property, the navigation method doesn't get called, and the same page gets rerendered with the button disabled or not rendered.
The more urget need is the answer to "how do i disable or hide the button?" of course,
But , since i guess the problem is due to jsf page life cycle and the bean scope, i'd like also to be direct to some tutorial a bit more advanced than the hello world that can be found around.
below are part of the code.
Thank you in advance for any help
the xhtml page
<ui:define name="content">
<p:layoutUnit position="center" header="Dettaglio Pratica" scrollable="true">
<h:form id="formDettaglioPratica">
<!-- i've used javascript to redirect -->
<p:commandButton styleClass="commandButton" value="Modifica pratica" ajax="false"
rendered="#{praticaCtrl.visible}" onclick="navigateToChange();return false;"/>
<p:commandButton id="backButton" styleClass="commandButton" value="Torna alla lista"
onclick="navigateToHome();return false;"></p:commandButton>
<!-- never redirect to page defined in method checkIn -->
<p:commandButton id="checkinButton" styleClass="commandButton" value="Rilascia pratica" ajax="false"
actionListener="#{praticaCtrl.checkIn}" disabled="#{praticaCtrl.visible}"></p:commandButton>
<!-- printing output values -->
<h:inputHidden id="idPratica" value="#{praticaCtrl.idPratica}"></h:inputHidden>
<h:inputHidden id="idBox" value="#{praticaCtrl.box}"></h:inputHidden>
</h:form>
</p:layoutUnit>
</ui:define>
the relevant part of the managed bean
public boolean isVisible() {
return isVisible;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public void setUser(IUserProvider user) {
try{
if(pratica.getUtenteCheckOut() == null
|| (pratica.getUtenteCheckOut().getMatricola().equalsIgnoreCase(user.getUser().getMatricola()))
)
setVisible(true);
else
setVisible(false);
this.user = user;
}
catch(Exception ex)
{log.error(ex);}
}
public void checkIn(ActionEvent event)
{
try{
log.info(String.format("modifica della pratica %s", idPratica));
ajaxRedirect(String.format("../Box/ListaRichieste.xhtml?box=%s",box));
}
catch(Exception ex)
{
log.error(ex.getMessage(),ex);
}
}
this is the ajaxRedirect method,we don't use the navigation rules neither methods return string
protected void ajaxRedirect(String url) throws IOException {
FacesContext.getCurrentInstance().getExternalContext()
.redirect(url);
}
the answer for the described behaviour can be found at : http://forum.primefaces.org/viewtopic.php?f=3&t=13269&p=39996 ,which refers a BalusC answer on a similar question on stackoverflow : commandButton/commandLink/ajax action/listener method not invoked or input value not updated

Resources