I have a PrimeFaces DataTable with a lot of entries. When I click a row I do this here:
<p:ajax event="rowSelect" listener="#{detailsBean.showData(data)}">
So what I want to do is to call a method in my bean and hand over the data from the clicked table row but when I debug it the object is always null. I'm not sure how to deal with this. Whats wrong?
Here's how I get the selected item from datatable
xhtml:
<p:datatable value="#{yourBean.listObject}" selection="single" ---- and other suff---->
<p:ajax event="rowSelect" listener=#"{yourBean.aMethodInBean}"/>
</p:datatable>
bean:
YourObject yourObject;
List<YourObject> listObject;
-----
public void aMethodInBean(SelectEvent event) {
yourObject = (YourObject) event.getObject();
}
Xhtml :
<p:dataTable value="#{bean.list}" selectionMode="single" selection="{bean.selectedEmployee}">
<p:ajax event="rowSelect" listener="#{bean.anyMethod()}"/>
</p:dataTable>
Here ajax is not mandatory
Bean :
List<Employee> list ;
Employee selectedEmployee;
public void anyMethod(){
}
Related
I have a <h:dataTable> with columns defined as this
<h:column>
<f:facet name="header">
<h:outputText value="Price"/>
</f:facet>
<h:outputText value="#{p.price}" rendered="#{not p.editable}"></h:outputText>
<h:inputText value="#{p.price}" rendered="#{p.editable}"></h:inputText>
</h:column>
The <h:dataTable> is populated successfully with
<h:dataTable id="userTable" value="#{gnome.productList}"
var="p">
The backing bean #gnome is a #ViewScoped bean, and the productList is loaded in a postconstructor and has a normal getter.
#PostConstruct
public void init() {
productList = gnomeFacade.findAll();
}
public List<Gnome> getProductList() {
return productList;
}
The <h:inputText> is rendered when an <h:commandLink> is pressed, and it allows me to modify the data in the fields. The data is then supposed to be saved using a <h:commandButton> defined outside the <h:dataTable>,
<h:commandButton value="Save changes!" action="#{gnome.saveAction}"/>
which invokes this method
public String saveAction() {
System.out.println("DEBUG: Trying to save edited gnome...");
for (Gnome g : productList) {
gnomeFacade.edit(g);
}
return null;
}
I have added some debug printouts in the gnomeFacade.edit() method, to be able to view what data is being merged. None of the properties in the productList entities are being saved with their new values. My initial thought was that the <h:dataTable> was reiterating over the values of the productList, but since I have it loaded in a postconstructor, that should not be the issue?
Why aren't the values of the properties changing when I change the values in the <h:inputText>?
Edit:
Full .xhtml document:
https://pastee.org/75t3e
Please read to the end, there are many EDITS I have this piece of JSF code:
<h:form>
<h:dataTable class="table-striped" var="_product"
value="#{productManager.products}"
border="1"
binding="#{productManager.table}">
<h:column>
<f:facet name="header">Product</f:facet>
#{_product.name}
</h:column>
<h:column>
<f:facet name="header">Available Units</f:facet>
#{_product.stock}
</h:column>
<h:column>
<f:facet name="header">Category</f:facet>
#{_product.category}
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
#{_product.price}
</h:column>
<h:column>
<f:facet name="header">Description</f:facet>
#{_product.description}
</h:column>
<h:column>
<f:facet name="header">Select</f:facet>
<h:commandButton class="btn btn-primary" value="Select"
action="#{productManager.selectProduct}"/>
</h:column>
</h:dataTable>
</h:form>
<h:form>
<h:outputLabel for="productName">Selected Product: </h:outputLabel>
<h:inputText value="#{productManager.selectedDesiredCategory}"/>
<h:commandButton value="Filter category" action="#{productManager.filterProductsByCategory}"/>
<h:outputText id="productName" value="#{productManager.selectedName}"/><br/>
<h:outputLabel for="units">Units: </h:outputLabel>
<h:inputText id="units" value="#{productManager.selectedUnits}"/>
<h:commandButton value="Add to basket" action="#{productManager.addToBasket(accountManager.username)}"/><br/>
<h:outputText rendered="#{productManager.availableMessages}"
value="#{productManager.message}"/>
</h:form>
The #{productManager.filterProductsByCategory} commandbutton redirects to this java method:
public void filterProductsByCategory() {
this.products = controller.obtainProductListByCategory(selectedDesiredCategory);
showMessage("Filtered by selected category");
}
Here I update the content of the products list with the new set of filtered-by-category products to display them in the view. The thing is the page is not reloading to display the new content. How is this achieved?
EDIT: The showMessage method is actually displaying in the view, so the page IS reloading, but for some reason the table is not updating. Maybe it's a problem with the data the query is returning, I'm actually researching.
EDIT: The query is returning good results, as my debugging process confirmed, but the webpage is not reloading the data properly in the table.
EDIT: I found out something really weird. This is the code the JSF page is referencing to:
public void filterProductsByCategory()
{
filtered = true;
products = controller.obtainProductListByCategory(selectedDesiredCategory);
showMessage("Filtered by selected category");
}
I'm now using a boolean value to actually know when I have to deliver a filtered list (See why in the code below) This is the getter of the products list:
public List<Product> getProducts()
{
if(filtered)
{
filtered = false;
return products;
}
products = controller.obtainProductList();
return products;
}
Here if it's true it should just send the actual filtered products variable. But for some reason it's looping again and again inside the method (even after the return statement inside the if) and sending all the products to the view again. Why is this even happening?
By default, JSF calls the getter methods as much as they're used in the view. For example, for your List<Product> products field and its respective getter, if #{productManager.products appears twice in your view i.e. in the Facelets code, then the getter will be executed twice as well. For this reason, getter and setter methods in managed bean should be as clean as possible and should not contain any business logic involved.
Basically, you should retrieve the product list from database once, after creating the managed bean and before the view render time. To achieve this, you can use #PostConstruct annotation to decorate a void method that will be executed after the bean is created.
In code:
#ManagedBean
#ViewScoped
public class ProductManager {
private List<Product> products;
#PostConstruct
public void init() { //you can change the method name
//if you manually handle the controller, initialize it here
//otherwise, let it be injected by EJB, Spring, CDI
//or whichever framework you're working with
products = controller.obtainProductList();
}
public List<Product> getProducts() {
//plain getter, as simple as this
//no business logic AT ALL
return this.products;
}
public void filterProductsByCategory() {
filtered = true;
products = controller.obtainProductListByCategory(selectedDesiredCategory);
//I guess this method logs a message or something...
showMessage("Filtered by selected category");
}
}
More info
Why JSF calls getters multiple times
Why use #PostConstruct?
I have my XHTML like this
<h:form id="form">
<h:panelGrid columns="3">
<h:outputText value="Keyup: " />
<p:inputText id="counter">
<p:ajax event="keyup" update="out"
listener="#{counterBean.increment}" />
</p:inputText>
<h:outputText id="out" value="#{counterBean.count}" />
</h:panelGrid>
</h:form>
Case I : ajax listener method with AjaxBehaviorEvent
public void increment(AjaxBehaviorEvent event) {
count++;
}
Case II : without AjaxBehaviorEvent
public void increment() {
count++;
}
In both the cases listener will be invoked and does the counter job to increase count on keyup. So, When exactly I need to use AjaxBehaviorEvent and when I don't need to use?
You can bind multiple ajax events to the same method and use getSource() of AjaxBehaviorEvent to know which component trigged the event.
I have a page with a datatable which have to display various informations about Mailbox objects. One of these informations is the owner of the Mailbox which is stored by its id in Mailbox object. In output I solved this with a method in backing bean that retrieve the username by the mailbox object. In input I thought to use autocomplete with pojo but I can't exactly realize how do this.
My jsf page:
<p:dataTable id="dataTable" value="#{bean.mailboxes}" var="m" editable="true">
<!-- other table -->
<p:column headerText="Owner">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{bean.userByMailbox(m)}" />
</f:facet>
<f:facet name="input">
<!-- here comes autocomplete -->
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
And my bean:
public class Bean {
// Other properties and methods
List<Mailbox> mailboxes;
public List<Mailbox> getMailboxes() {
if (mailboxes == null) {
Query q = em.createNamedQuery("Mailbox.findAll");
mailboxes = q.getResultList();
}
return mailboxes;
}
public User getUserByMailbox(Mailbox m) {
Query q = em.createNamedQuery("User.findByUsrId");
q.setParameter("usrId", m.getUsrId());
return (User)q.getSingleResult();
}
}
Thank you all!
Your model is wrong.
In Mailbox, replace
#Column
private Long usrId;
by
#ManyToOne
#JoinColumn(name="usrId")
private User user;
This way you can just use#{m.user} instead of #{bean.userByMailbox(m)}. This way the property is also writable (perhaps you actually got a PropertyNotWritableException while attempting to use this EL expression in <p:autoComplete value>; in the future questions tell that so instead of asking an overly generic question).
Note that this concrete problem has essentially nothing to do with JSF nor <p:autoComplete>.
I am using primefaces for not so long and Ive found that I cant use a <p:commandButton /> because it just can't reach the method, the method is ok, I tried it out of the table (and the subtable) and it works perfectly there (everything is inside a form) , the problem is that I need the user to be able to select all the subtable, so, I thought maybe with a button that could be possible, but seems like subtable doesn't allow that, any other way I can do this? or maybe I have to use another way for call my method from a subtable, anybody knows about it?
Thanks
some of my code
<h:form>
<p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" />
<p:dataTable id="case" var="ticket" value="#{CaseBean.selectedCase.tickets}">
<p:columnGroup>
<p:row>
<p:column> Action:</p:column>
<p:column>
<!-- This doesn't work, removed. -->
<p:commandButton value="Aprove" action="#{CaseBean.acept()}">
</p:commandButton>
</p:column>
</p:row>
</p:columnGroup>
<p:subTable var="detail" value="#{ticket.detail}">
<f:facet name="header">
Resume:
</f:facet>
<!-- some data... -->
<p:column>
<!-- doesn't work either -->
<p:commandButton value="Aprove" action="#{CaseBean.aceptTicket()}">
</p:commandButton>
</p:column>
<!-- show my data -->
The table works perfectly, it shows all the data, the log files doesn't show any error, so, when I tried to write my commandButton out of the table it worked perfectly, if I cant write it inside a subtable its ok, but , how could I write it in the table? it doesn't show up there either.
you welcome :)
But if i was you I wouldn't use subtables, Ill think for another solution..maybe Ill do it this way, ill use two different data tables, the first contains the parent list and the second one contains the child list elements, and every selection made triggers an update of the second table...I tried it on my IDE and it works just fine
<h:form id="form">
<p:dataTable var="cas" value="#{beanCase.myListOfCase}"
selection="#{beanCase.selectedCase}" rowKey="#{cas.idCase}"
selectionMode="single">
<p:ajax event="rowSelect" update=":form:TicketTable" />
<p:column headerText="Id Case">
<h:outputText value="#{cas.idCase}" />
</p:column>
<p:column headerText="Case Name ">
<h:outputText value="#{cas.caseName}" />
</p:column>
<p:column headerText="Case Detail">
<h:outputText value="#{cas.caseDetail}" />
</p:column>
<p:column headerText="Action">
<p:commandButton value="Accept Case" update=":form:TicketTable"></p:commandButton>
</p:column>
</p:dataTable>
<p:dataTable id="TicketTable" var="ticket"
value="#{beanCase.selectedCase.tickets}">
<p:column headerText="Ticket Number">
<h:outputText value="#{ticket.idTicket}" />
</p:column>
<p:column headerText="Ticket Details">
<h:outputText value="#{ticket.labelTicket}" />
</p:column>
<p:column headerText="show">
<h:outputText value="#{ticket.show}" />
</p:column>
<p:column headerText="this show is brought to you by">
<h:outputText value="#{ticket.sponsor}" />
</p:column>
<p:column headerText="Make a Reservation">
<p:commandButton value="Buy" action="#{beanCase.buyTicket()}">
<f:setPropertyActionListener value="#{ticket}"
target="#{beanCase.selectedTicket}" />
</p:commandButton>
</p:column>
</p:dataTable>
before that you must create the data model classes for the Case and ticket
public class CaseDataModel extends ListDataModel<Case> implements
SelectableDataModel<Case> {
CaseDAO caseDAO = new CaseDAO();
public CaseDataModel() {
}
public CaseDataModel(List<Case> cases) {
super(cases);
}
#Override
public Case getRowData(String arg0) {
List<Case> listOfMyObjet = (List<Case>) caseDAO.findAll();
for (Case obj : listOfMyObjet) {
if (String.valueOf(obj.getIdCase()).equals(arg0))
;
return obj;
}
return null;
}
#Override
public String getRowKey(Case arg0) {
return String.valueOf(arg0.getIdCase());
}
}
The first columnGroup is not rendered because in your first row the number of columns is 2, one for "action" and the other for the commandButton while in your subtable you just used two rows one for "Resume" and other contains only one Column for the other commandButton.
The number of columns should be the same in every row, so you must use colspan or rowspan to make sure of that.
As for the rest using a DataTable will do the job, I didn't understand what you wanna do exactly but I all assume that you want to select myObject from displayed list of objects within a dataTable. So in order to achieve that, the UidataTable must return an object to the backed Bean.
public class myObjectDataModel extends ListDataModel<myObject> implements SelectableDataModel<myObject> {
public myObjectDataModel() {
}
public myObjectDataModel(List<myObject> data) {
super(data);
}
#Override
public myObject getRowData(String rowKey) {
List<myObject> listOfMyObjet = (List<myObject>) yourDao.getListOfmyOjects();//get your list
for(myObject obj : listOfMyObjet) {
if(obj.getIdObject().equals(rowKey))
return obj;
}
return null;
}
#Override
public Object getRowKey(myObject obj) {
return obj.getIdObject();
}
}
The backed bean:
public class tableBean {
private List<myObject> _Objects;
private myObjectDataModel myListOfObjects;
private myObject selectedObject;
//getters and setters
public tableBean(){
myObjectDataModel = new myObjectDataModel(_Objects);
}
//...
}
xhtml:
<p:dataTable id="table" var="case"
value="#{tableBean.myObjectDataModel}"
selection="#{tableBean.selectedObject}" selectionMode="single"
rowKey="#{case.IdObject}">
<p:column>
<p:commandButton value="
Aprove" action="#{tableBean.someMethod()}">
</p:commandButton>
</p:column>
</p:dataTable>
and make sure to use Ajax — commandButton update attribute, or <p:ajax> — to refresh your UI.
Try removing the p:columnGroup from your JSF page. You don't need it for this (and this might be the cause of your problem). Think of it like this: a table exists of rows and rows exist of columns. ;-)
The #{CaseBean} has got to be in the view scope in order to get this to work, or if you want to keep it request scoped, the #{CaseBean.selectedCase.tickets} has to prepared in the (post)constructor on some request parameters so that it's exactly the same as it was during displaying the table.
When the form is submitted, JSF will namely reiterate over the table in order to find the command component responsible for the action. However, if the bean is request scoped and the value behind #{CaseBean.selectedCase} or #{CaseBean.selectedCase.tickets} is not the same as it was during displaying the table, then JSF won't be able to identify the button which invoked the action.
See also:
commandButton/commandLink/ajax action/listener method not invoked or input value not updated - point 4 applies to you