Navigate to another page on rowselect of datatable in primefaces - ajax

I have a primefaces datatable where number of records are displaying.
I want navigate to another page on the rowSelect event (to edit the selected entity for example).
The closest sample/demo I could find was use the p:ajax tag to bind the rowSelect event to a listener method
http://www.primefaces.org/showcase-labs/ui/datatableRowSelectionInstant.jsf
I also got one article for the same http://forum.primefaces.org/viewtopic.php?f=3&t=14664
, I tried to implement in same as they did.But it also didn't worked.
I am trying in this way and guide me If I missed anything.
<p:dataTable var="product" value="#{addPatientBB.patientAddList}" paginator="true" rows="10"
selection="#{addPatientBB.pat}" selectionMode="single">
<p:ajax event="rowSelect" listener="#{addPatientBB.onRowSelect}" />
<p:column>
<f:facet name="header">
<h:outputText value="FirstName" />
</f:facet>
<h:outputText value="#{product.firstName}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Email" />
</f:facet>
<h:outputText value="#{product.email}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="Gender" />
</f:facet>
<h:outputText value="#{product.gender}" />
</p:column>
</p:dataTable>
And Backing bean is :
#ManagedBean
#ViewScoped
public class AddPatientBB implements Serializable
{
private Patient pat;
public Patient getPat()
{
System.out.println("tried to get pat");
return pat;
}
public void setPat(Patient pat)
{
this.pat = pat;
System.out.println("tried to set pat");
}
public void onRowSelect()
{
System.out.println("inside onRow select Method");
ConfigurableNavigationHandler configurableNavigationHandler = (ConfigurableNavigationHandler) FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
System.out.println("navigation objt created");
configurableNavigationHandler.performNavigation("Page?faces-redirect=true");
// Page is my navigation page where I wish to navigate named as
// "Page.xhtml"
System.out.println("Navigation executed");
}
}
So how can I navigate to another page on rowselect event? and how can display its values after navigationg the form.
I am able to go inside onRowSelect() method , actually problem is he is not able to get or understood that path :
configurableNavigationHandler.performNavigation("Page?faces-redirect=true");
so he is not able to print any logs after this line.
why is it so? is it because of I am using Liferay?
Pla guide me.

Well i think the onRowSelect is never executed because you defined it wrong.
Try this:
public void onRowSelect(SelectEvent event)
{
FacesContext.getCurrentInstance().getExternalContext().redirect("page.xhtml?id=" +pat.getId());
}

If u are using FacesServlet then use.jsf instead of .xhtml
public void onRowSelect(SelectEvent event)
{
FacesContext.getCurrentInstance().getExternalContext().redirect("page.jsf?id="+pat.getId());
}

Related

Site doesn't reload after button click

I developed a view to save Child-objects. Everything works fine but to see my additional objects in the <p:dataTable> I always have to reload the site manually.
Below the code for the <p:commandButton> which sends the form-data to my controller class.
<h:panelGrid columns="3">
<p:commandButton value="Save"
action="#{childController.doSaveChild}"
oncomplete="PF('childAddDialog').hide()"
update=":childForm"/>
</h:panelGrid>
I already tried to use ajax="false", but it doesn't work.
What can I do to get the site reloaded after click on save-button?
UPDATE:
<p:dataTable> from my view.xhtml:
<h:form id="childForm">
<p:dataTable id="childTable" var="child"
widgetVar="childTable" value="#{childController.children}"
paginator="true" rows="10" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink}
{PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}
{Exporters}"
rowsPerPageTemplate="10,25,50">
<p:column headerText="Firstname"
filterBy="#{child.firstName}"
sortBy="#{child.firstName}" filterStyle="display:none">
<h:outputText value="#{child.firstName}"/>
</p:column>
<p:column headerText="Lastname"
filterBy="#{child.lastName}"
sortBy="#{child.lastName}"
filterStyle="display:none">
<h:outputText value="#{child.lastName}"/>
</p:column>
<p:column headerText="Birthday"
filterBy="#{child.birthday}"
sortBy="#{child.birthday}"
filterStyle="display:none">
<h:outputText value="#{child.birthday}"/>
</p:column>
</dataTable>
</form>
Here the methods for providing the children for the view:
public Collection<Child> getChildren(){
return children;
}
#PostConstruct
public void initList(){
setChildren(childService.getAllChildren());
}
The xhtml-code from above is fine.
To get the site auto-updated it is necessary to load the list with all children again after the save-method in controller.
public void doSaveChild(){
childService.saveChild(child);
child = null;
initNewChild();
initList(); //this is needed to get up-to-date list in view
}
You could either do it via javascript:
<p:commandButton value="Save"
action="#{childController.doSaveChild}" process="#form" update="#none" oncomplete="location.reload();"/>
or a return String in your action method:
public String doSaveChild(){
//your logic
return "/yourpage?faces-redirect=true"}

ActionListener not calls with ajax=false

I'm facing a strange issue with JSF, primefaces 5.2, glassfish 4, CDI ViewScoped Named beans. I've searched the forum but mostly people got stuck with ajax not working, while here Command button actionListener works with process="#form" but with ajax="false" it does not, rather just a full page refresh occurs. What i
understand that JSF default behavior is process="#form" but here i have to explicitly define it, without which ajax does not work. I've double checked and there are no nested forms in the hierarchy. Could it be something wrong with my development environment or am i doing something terribly wrong. Here is my jsf page
<h:panelGroup id="selectedtestpanel3">
<h:form id="SelectedTests3" >
<p:dataTable id="selectedTestDataTable3" value="#{aTestRegController.testprofilelist}" var="seltestprofile"
rowKey="#{aTestRegController.selectedToString(seltestprofile)}" tableStyle="width:auto" resizableColumns="true"
selectionMode="single" selection="#{aTestRegController.selected}" style="vertical-align:top;"
>
<p:ajax event="rowSelect" listener="#{aTestRegController.testprofilePull(aTestRegController.selected)}"
update="patientRegWizard:SelectedTests3, patientRegWizard:displayprices"/>
<p:column headerText="Test/Profile Name" width="10">
<h:outputText value="#{aTestRegController.selectedTestProfileName(seltestprofile)}"/>
</p:column>
<p:column headerText="Price" width="10">
<h:outputText value="#{aTestRegController.selectedTestProfilePrice(seltestprofile)}"/>
</p:column>
<p:column headerText="Container" width="10">
<h:outputText value="#{aTestRegController.selectedTestProfileContainer(seltestprofile)}"/>
</p:column>
</p:dataTable>
<p:commandButton id="saveReg" icon="ui-icon-plus" value="Save Test Registration01"
actionListener="#{aTestRegController.createVoucher()}"
disabled="#{empty aTestRegController.testprofilelist}"
ajax="false"
/>
</h:form>
</h:panelGroup>
Here are some lines of managed bean
#Named("aTestRegController")
#ViewScoped
public class ATestRegController implements Serializable {
#EJB
private facades.PatientFacade patientFacade;
#Inject
private facades.VoucherFacade voucherFacade;
#Inject
private facades.TestFacade testFacade;
public void createVoucher(){
this.biolist2=null;
this.hemolist2=null;
this.microlist2=null;
this.speclist2=null;
this.radiolist2=null;
try{
//if(this.getItem()!=null){
if(true){
tempSessionVars();
this.item=fillVoucher();
this.create();
List<Voucherdetails> cashvdlist = new ArrayList<>(this.item.getVoucherdetailsCollection());
String testprofilecashsliplist=AReportPrint.convertVoucherdetailsToString(cashvdlist);
AReportPrint.printCashSlip(testprofilecashsliplist, item);
iterateSelection();
profilelist=new ArrayList();
profilemap.clear();
testlist=new ArrayList();
testmap.clear();
}
}catch(Exception e){
e.printStackTrace();
}
}

Update single row in JSF / Primefaces datatable using AJAX

How could I update a single row in a p:datatable when using AJAX?
I don't want to update the whole datatable because it has a lot of rows and it's going to take some time..
My layout:
<h:form id="visitForm">
<p:dataTable id="visitTable" var="visit" value="#{visitBean.findAllVisits()}">
<p:column headerText="${msgs['email']}"
<h:outputText value="#{visit.contactDetail.email}"/>
</p:column>
<p:column headerText="${msgs['clearance']}" id="clearance">
<p:commandButton value="${msgs['clearance.ok']}" actionListener="#{visitBean.makeClearanceNotOk(visit)}"/>
</p:column>
</p:dataTable>
</h:form>
I've tried out some things like update = "clearance" etc but it doesn't seem to work.
I'm using JSF 2.1 and Primefaces 5.2
You can use #row(n) search expression which does just that - it updates the nth row in a table. In order to update the current row, you need to pass row index as an argument. Set rowIndexVar="rowIdx" attribute on <p:dataTable> and then:
<p:commandButton ... update="#form:visitTable:#row(#{rowIdx})" />
Not sure if I'm late for the party but let me give my 5 cents on this subject on how to update content of a row using just plain ajax features from PrimeFaces.
1) Partial update: My first approach to update something in a specific row using PF is not exactly update the whole row, but update the regions of interest inside the row. This can be achieved by just defining the holding panels and updating them. For example:
<h:form id="testForm">
<p:dataTable id="myEntityTable" var="myEntity" value="#{myController.allEntities}">
<p:column headerText="id">
<h:outputText value="#{myEntity.id}"/>
</p:column>
<p:column headerText="last update">
<p:outputPanel id="lastUpdatePanel">
<h:outputText value="#{myEntity.lastUpdate}">
<f:convertDateTime pattern="HH:mm:ss" type="date" />
</h:outputText>
</p:outputPanel>
</p:column>
<p:column headerText="counter">
<p:outputPanel id="counterPanel">
<h:outputText value="#{myEntity.counter}"/>
</p:outputPanel>
</p:column>
<p:column headerText="increment">
<p:commandButton value="+"
actionListener="#{myController.increment(myEntity)}"
update="counterPanel, lastUpdatePanel"/>
</p:column>
</p:dataTable>
</h:form>
The trick is to update the target panels (in this example the fragment update="counterPanel, lastUpdatePanel"). This results in something like the following image:
2) Actually updating the row: Very often the previous approach works fine enough. However, if it is really needed to update the row one can follow the advice given in one of the previous answers and use the #row keyword:
<h:form id="testForm">
<p:dataTable id="myEntityTable" var="myEntity" value="#{myController.allEntities}" rowIndexVar="rowIndex">
<p:column headerText="id">
<h:outputText value="#{myEntity.id}"/>
</p:column>
<p:column headerText="last update 1">
<p:outputPanel>
<h:outputText value="#{myEntity.lastUpdate}">
<f:convertDateTime pattern="HH:mm:ss" type="date" />
</h:outputText>
</p:outputPanel>
</p:column>
<p:column headerText="last update 2">
<h:outputText value="#{myEntity.lastUpdate}">
<f:convertDateTime pattern="HH:mm:ss" type="date" />
</h:outputText>
</p:column>
<p:column headerText="counter">
<p:outputPanel>
<h:outputText value="#{myEntity.counter}"/>
</p:outputPanel>
</p:column>
<p:column headerText="increment">
<p:commandButton value="+"
actionListener="#{myController.increment(myEntity)}"
update="#form:myEntityTable:#row(#{rowIndex})"/>
</p:column>
</p:dataTable>
</h:form>
The trick is to hold each content from the columns inside a p:outputPanel and let update="#form:myEntityTable:#row(#{rowIndex})" make the job. I consciously leave the "last update 2" column without an outputPanel in order to illustrate this point:
Hence, whereas the columns "last update 1" and "counter" actually update after a click in "+" the "last update 2" column keeps unchanged. So, if you need to update a content, wrap up it with an outputPanel. It is noteworthy as well that the outputPanels holding each column content don't need an explicit id (you can add one if you want).
In the sake of completeness, in these examples I have used PF 6.2. The backbean is pretty straightforward:
package myprefferedpackage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class MyController {
private List<MyEntity> entities;
#PostConstruct
public void init() {
this.entities = new ArrayList<MyEntity>(10);
for(int i = 0; i < 10; ++i) {
this.entities.add(new MyEntity(i));
}
}
public List<MyEntity> getAllEntities() {
return entities;
}
public void increment(MyEntity myEntity) {
myEntity.increment();
}
public class MyEntity {
private int id;
private int counter;
private Date lastUpdate;
public MyEntity(int id) {
this.id = id;
this.counter = 0;
this.lastUpdate = new Date();
}
public void increment() {
this.counter++;
this.lastUpdate = new Date();
}
public int getId() {
return id;
}
public int getCounter() {
return counter;
}
public Date getLastUpdate() {
return lastUpdate;
}
}
}
Either use the 'ajax' functionality of a utility library like OmniFaces or be creative with the PrimeFaces Selectors.
In both cases you need to get access to the e.g. the 'current' row or rowId. But since that you have the buttons IN the row, that should not be a problem. I unfortunately don't have the time to create examples for you
I try with uptate = "#parent:componentAnotherColumn" and works. Only update the same row
<p:column>
<p:selectBooleanCheckbox value="#{atributoVar.booleanValue}">
<p:ajax process="#this" update="#parent:componentAnotherColumn"/>
</p:selectBooleanCheckbox>
</p:column>
<p:column>
<p:selectBooleanCheckbox id="componentAnotherColumn" value="#{!atributoVar.booleanValue}"/>
</p:column>

Primefaces "sortBy=" doesn't work

I'm developing an application using Primefaces + JSF. My data table works, but has a problem at sort sortBy=, I tried sortBy="#{pc.rota}" but it doesn't work too:
Data table show all rows, the problem I think is sortBy= or my backing bean.
page.xhtml
<h:body>
<h:form id="pcEmulation">
<p:dataTable id="dataTablePCEMulation" var="pc" value="#{pCEmulationBean.allPCEmulation}"
rows="10"
rowsPerPageTemplate="5,30,50,100,200,300"
emptyMessage="Não foi encontrado"
>
<f:facet name="header">
PC Emulation Web
</f:facet>
<p:column headerText="PC - TX OLO's" filterValue="#{pc.filtpcn}" filterMatchMode="contains" filterBy="#{pc.filtpcn}" >
<h:outputText value="#{pc.filtpcn}" />
</p:column>
<p:column headerText="Rota" sortBy="rota" >
<h:outputText value="#{pc.rota}" />
</p:column>
<p:column headerText="Origem">
<h:outputText value="#{pc.origem}" />
</p:column>
<p:column headerText="Antigo">
<h:outputText value="#{pc.epcn}" />
</p:column>
<p:column headerText="Destino">
<h:outputText value="#{pc.destino}" />
</p:column>
<p:column headerText="PC-Novo">
<h:outputText value="#{pc.realpcn}" />
</p:column>
</p:dataTable>
<p:blockUI block="dataTablePCEMulation" trigger="dataTablePCEMulation">
LOADING<br />
<p:graphicImage value="/images/loading.gif"/><br />
<p:graphicImage value="/images/tim-banner2.png" width="100px" height="45px"/>
</p:blockUI>
</h:form>
</h:body>
Backing bean:
#ManagedBean
//#ViewScoped
#SessionScoped
public class PCEmulationBean {
public List<PCEmulation> allPCEmulation;
public List<PCEmulation> getAllPCEmulation() {
PCEmulationDAO dao = new PCEmulationDAO();
try {
allPCEmulation = dao.getAll();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Problema no metodo list : " + e);
}
return allPCEmulation;
}
}
For the sort to work you need to return the same list object each time with the getter, where in your case you are returning a new list from the dao every time. So you should only fetch a new list if the list is previously null. The code inside your getter should be as below.
if (allPCEmulation == null) {
PCEmulationDAO dao = new PCEmulationDAO();
try {
allPCEmulation = dao.getAll();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Problema no metodo list : " + e);
}
}
return allPCEmulation;
As far as I know, sortBy attribute of Datatable is applied for only Primitive Data Types and String. If rota is an object, you must create method for sorting by yourself. Alternative, using sortBy="#{pc.rota.someting}" that contain Primitive Data Types or String for sorting.

DataTable Order by column erase values

I have PrimeFaces dataTable that is been filled by a Ajax call.
When I click on a column title, to order its values, the values disappear.
<p:commandButton value="Pesquisar" actionListener="#{requestController.listRequests}" update="dataTable" />
Here is my view:
<p:dataTable id="dataTable" var="order" value="#{requestController.backing.requestsList}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}">
<p:column sortBy="#{order.companyRequest}">
<f:facet name="header">
<h:outputText value="Pedido" />
</f:facet>
<h:outputText value="#{order.companyRequest}" />
</p:column>
<p:column sortBy="#{order.company.companyName}">
<f:facet name="header">
<h:outputText value="Cliente" />
</f:facet>
<h:outputText value="#{order.company.companyName}" />
</p:column>
<p:column sortBy="#{order.emissionDate}">
<f:facet name="header">
<h:outputText value="Data" />
</f:facet>
<h:outputText value="#{order.emissionDate}">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:outputText>
</p:column>
<p:column sortBy="#{order.requestSituation.description}">
<f:facet name="header">
<h:outputText value="Status" />
</f:facet>
<h:outputText value="#{order.requestSituation.description}" />
</p:column>
<p:column>
<f:facet name="header">
</f:facet>
<h:form>
<h:commandLink value="Detalhes"/>
</h:form>
</p:column>
</p:dataTable>
EDIT
RequestController
#ManagedBean
#RequestScoped
public class RequestController implements Serializable
{
private RequestBacking backing;
public RequestController()
{
backing = new RequestBacking();
}
public void changeEventListener(ValueChangeEvent e)
{
backing.requestSearchType = e.getNewValue().toString();
}
public void change()
{
switch (backing.requestSearchType)
{
case "data":
backing.mask = "99/99/9999";
backing.maskSize = "10";
break;
case "cnpj":
backing.mask = " 99.999.999/9999-99";
backing.maskSize = "20";
break;
default:
backing.mask = "";
backing.maskSize = "50";
}
}
public void listRequests() throws ParseException
{
CompanyVO companyVO = new CompanyVO();
switch (backing.requestSearchType)
{
case "cnpj":
companyVO.setCnpj(backing.requestSearchValue);
break;
case "cliente":
companyVO.setCompanyName(backing.requestSearchValue);
break;
case "pedido":
backing.requestVO.setCompanyRequest(Integer.parseInt(backing.requestSearchType));
break;
}
SupplierVO supplierVO = new Support().getUserSession().getSupplier();
backing.requestVO.setEmissionDate(new Support().convertDate(backing.requestSearchValue));
backing.requestVO.setSupplier(supplierVO);
backing.requestVO.setCompany(companyVO);
backing.requestsList = new ArrayList<>(backing.getBo().getRequest(backing.requestVO));
if (backing.requestsList.isEmpty())
{
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_WARN, "Nenhum registro encontrado!", null);
FacesContext.getCurrentInstance().addMessage(null, facesMessage);
backing.requestsList = null;
}
}
..backing getter and setter
}
My requestsList is on my RequestBacking where I have all my getters and setters, please correct me if there is a better way of doing this, I'm using it because it leaves my controller cleaner.
public List<RequestVO> requestsList;
Apparently the value="#{requestController.backing.requestsList}" didn't return the same value as it did on the initial request. That can happen if it's a request scoped bean and/or if the requestsList is populated on every request based on a request based variable.
That's just a design mistake. Put the managed bean in the view scope and make sure that you aren't doing any business logic in a getter method. The nested class backing is also suspicious or it must be a poor naming.
See also:
Why JSF calls getters multiple times
How to choose the right bean scope?
Update in a nutshell, your bean should look something like this:
#ManagedBean
#ViewScoped
public class Orders {
private String query; // +getter +setter
private List<Order> results; // +getter (no setter required)
#EJB
private OrderService service;
public void search() {
results = service.search(query);
}
// Add/generate normal getters/setters (don't change them!)
}
and your view should look like this:
<h:form>
<p:inputText value="#{orders.query}" />
<p:commandButton value="Search" action="#{orders.search}" update=":tableForm" />
</h:form>
<h:form id="tableForm">
<p:dataTable value="#{orders.results}" var="order" ... rendered="#{not empty orders.results}">
...
</p:dataTable>
<h:outputText value="No results found" rendered="#{facesContext.postback and empty orders.results}" />
</h:form>

Resources