I am new to JSF. I am using row editable data table in JSF primefaces. In row editable datatable input text column it have two ajax calls.one is blur and another one is Commandbuuton. I want to get value from this input text column from backing bean.
Here is my Code:
<h:form id="frm1">
<p:dataTable var="fert" value="#{fertilizerEntryBean.fertList}" id="fertList" editable="true" scrollable="true" scrollWidth="900" scrollHeight="250" >
<p:ajax event="rowEdit" listener="#{fertilizerEntryBean.onEdit}" update=":frm1:messages :frm1:ha_amount" />
<p:ajax event="rowEditCancel" listener="#{fertilizerEntryBean.onCancel}" update=":frm1:messages :frm1:ha_amount" />
<p:column headerText="...." width="15">
<p:rowEditor />
</p:column>
<p:column headerText="Receiver Plot No." width="150">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{fert.receiverPlot}" /></f:facet>
<f:facet name="input">
<p:inputText id="receiverPlot" value="#{fert.receiverPlot}" size="15">
<p:ajax event="blur" listener="#{fertilizerEntryBean.loadReceiverDetails(fert)}" update="receiverCode,receiverName"/>
</p:inputText>
<p:commandButton icon="ui-icon-search" style="height: 25px;position: absolute;" onclick="receiver_dialog.show();"/>
</f:facet>
</p:cellEditor>
</p:column>
</p:datatable>
</h:form>
<h:form id="receiverForm">
<p:dialog widgetVar="receiver_dialog" id="receiver_dialog">
<p:dataTable id="receiver_table" value="#{fertilizerEntryBean.mediumFertModel}" selection="#{fertilizerEntryBean.selectedList}" selectionMode="single" var="fert" rows="10" liveScroll="true" paginator="true" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,20">
<p:ajax event="rowSelect" listener="#{fertilizerEntryBean.onRowSelect}" update=':frm1:fertList:receiverPlot'/>
<p:column id="state_id_column" headerText="Receiver Code">
<h:outputText value="#{fert.receiverPlot}"/>
</p:column>
</p:dataTable>
<p:commandButton style="alignment-adjust: central;" value='OK' onclick="receiver_dialog.hide();"/>
</p:dialog>
</h:form>
And my Bean Class:
public class FertilizerEntryBean implements Serializable{
private List<FertModel> fertList=null;
private FertDataModel mediumFertModel;
private FertModel selectedList;
public List<FertModel> getFertList() {
return fertList;
}
public void setFertList(List<FertModel> fertList) {
this.fertList = fertList;
}
public FertDataModel getMediumFertModel() {
getReceiverCode();
return mediumFertModel;
}
public void setMediumFertModel(FertDataModel mediumFertModel) {
this.mediumFertModel = mediumFertModel;
}
public FertModel getSelectedList() {
return selectedList;
}
public void setSelectedList(FertModel selectedList) {
this.selectedList = selectedList;
}
public List<FertModel> getReceiverCode(){
Session session=HibernateUtil.getSessionFactory().openSession();
try{
List<DosVendormaster> vendorList=session.createCriteria(DosVendormaster.class).add(Restrictions.eq("vendortype", "CGRV")).add(Restrictions.eq("block", "X")).list();
if(vendorList.size()>0){
for (Iterator<DosVendormaster> it = vendorList.iterator(); it.hasNext();) {
DosVendormaster dosVendormaster = it.next();
fertList.add(new FertModel(dosVendormaster.getSapVendorcode()));
}
mediumFertModel=new FertDataModel(fertList);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
session.close();
}
return fertList;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage(" Selected", ((FertModel) event.getObject()).getReceiverPlot());
FacesContext.getCurrentInstance().addMessage(null, msg);
FertModel fert=new FertModel();
fert.setReceiverPlot(((FertModel) event.getObject()).getReceiverPlot());
}
}
You can try this: FacesContext.getCurrentInstance().getViewRoot().findComponent(id) where id is something like frm1:fert:(rowIndex):receiverPlot. That's how you can find component and use getValue for that component. You can take rowIndex by setting rowIndexVar attributte to your datatable
Related
I have a table p:dataTable. When I select an item, it's refresh another p:dataTable with associed values.
It's works fine. But when I select an item in the second table, the page (xhtml) don't get the value from the bean.
In debug mode I see that the value is updated on bean, but acessing #{bean.value} is always null.
Where is the codes:
<h:form id="form">
<h:panelGrid columns="2">
<!-- FRIST TABLE -->
<p:dataTable id="alunos" var="aluno" emptyMessage="Nenhum aluno cadastrado" value="#{alunos.usuarios}" selectionMode="single" selection="#{alunos.usuarioSelecionado}" rowKey="#{aluno.id}">
<f:facet name="header">
Alunos
</f:facet>
<p:ajax event="rowSelect" listener="#{alunos.onRowSelect}" update=":form:disci" />
<p:column headerText="Nome" width="60%">
<h:outputText value="#{aluno.nome}" />
</p:column>
<p:column headerText="Curso">
<h:outputText value="Default" />
</p:column>
</p:dataTable>
<!-- FUNCTIONS FOR FRIST TABLE THAT ARE WORKING -->
<p:column rowspan="4">
<p:commandButton value="Adicionar" update="alunos" icon="ui-icon-plus" actionListener="#{alunos.addUser()}"/>
<p:commandButton value="Editar" icon="ui-icon-pencil" actionListener="#{alunos.editarUser()}"/>
<p:commandButton value="Remover" icon="ui-icon-close" actionListener="#{alunos.apagaUser()}"/>
</p:column>
</h:panelGrid>
<p:outputLabel for="disci" value="Disciplinas que o aluno cursa" />
<!-- SECOND TABLE - Updated when an iten is selected in frist table (working)-->
<p:dataTable id="disci" var="disciplina" emptyMessage="Selecione um aluno" value="#{alunos.disciplinas}" selectionMode="single" selection="#{alunos.disciplinaSelecionada}" rowKey="#{disciplina.id}">
<p:ajax event="rowSelect" listener="#{alunos.onRowSelectDisciplina}" oncomplete="PF('dDialog').show()"/>
<p:column headerText="Nome" width="80%">
<h:outputText value="#{disciplina.nome}" />
</p:column>
</p:dataTable>
<!-- Dialog to show informations - ALWAYS NULL -->
<p:dialog header="Info" widgetVar="dDialog" modal="true" showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="detail" style="text-align:center;">
<p:panelGrid columns="2" columnClasses="label,value">
<h:outputText value="Id:" />
<h:outputText value="#{alunos.disciplinaSelecionada.id}" />
<h:outputText value="Nome" />
<h:outputText value="#{alunos.disciplinaSelecionada.nome}" />
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
And the Bean:
#ManagedBean(name = "alunos")
#ViewScoped
public class Alunos extends NovoUsuario {
private Disciplina disciplinaSelecionada;
public Alunos() {
super(TiposUsuario.ALUNO);
}
//Method called when an iten is selected in SECOND TABLE
//In debug, the Object Disciplina is correct, as selected in table.
public void onRowSelectDisciplina(SelectEvent event) {
this.disciplinaSelecionada = (Disciplina) event.getObject();
}
//getters and setters
}
extended class:
public class NovoUsuario implements Serializable{
private List<Usuario> usuarios;
protected Usuario usuarioSelecionado;
TiposUsuario tipo;
private String nome;
private String senha;
protected List<Disciplina> disciplinas;
//Constructor
public NovoUsuario(TiposUsuario tipo) {
this.tipo = tipo;
}
//Initialize FRIST TABLE
#PostConstruct
public void init() {
UsuarioCRUD usuarioCRUD = new UsuarioCRUD();
this.usuarios = usuarioCRUD.listarTipoUsuario(tipo);
}
//Method used in FRIST TABLE
public void onRowSelect(SelectEvent event) {
disciplinas = getDisciplinaUsuario();
}
//Method that get data to SECOND table when a row is selectd in frist
public List<Disciplina> getDisciplinaUsuario() {
DisciplinaCRUD dcrud = new DisciplinaCRUD();
if (usuarioSelecionado != null) {
return dcrud.listaDisciplinasUsuario(usuarioSelecionado);
}
return null;
}
public void salvaUsuario() {
/* code to create*/
}
public void editarUser(){
/* code to update*/
}
public void apagaUser(){
/* code to delete*/
}
//GETTERS AND SETTERS
}
image: http://i.stack.imgur.com/Qbs0T.png
repository: https://bitbucket.org/VagnerGon/novo-academico
I'd say you just need to update the dialogs content from the p:ajax in the second table - just as you update the second datatable, when you select in the first.
So add id="dialog" to the dialog, and make the p:ajax in the second table
<p:ajax event="rowSelect" listener="#{alunos.onRowSelectDisciplina}" update=":form:dialog" oncomplete="PF('dDialog').show()" />
Or omit the new id and just do update=":form:detail".
I have an Office datatable that displays department name and role name. department and role are objects. when I select rowedit, when there is a change in the department, the roles should be reloaded. I am not sure how to pass the selected department and rerender the roles.
<p:column headerText="Department">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{office.department.name}" /></f:facet>
<f:facet name="input">
<p:selectOneMenu value="#{office.department}" converter="#{departmentConverter}" style="width:96%" >
<f:selectItems value="#{departments}" var="dept" itemLabel="#{dept.name}" itemValue="#{dept}"/>
<p:ajax event="change" listener="#{officeManagmentController.onDepartmentChanged()}"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Role">
<p:cellEditor>
<f:facet name="output"><h:outputText value="#{office.role.name}" /></f:facet>
<f:facet name="input">
<p:selectOneMenu value="#{office.role}" converter="#{roleConverter}" style="width:96%" >
<f:selectItems value="#{officeManagementController.assignableRoles}" var="role" itemLabel="#{role.name}" itemValue="#{role}"/>
</p:selectOneMenu>
</f:facet>
</p:cellEditor>
</p:column>
the following is my officecontroller managedbean
#ConversationScoped
public class OfficeManagementController implements Serializable {
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage(selectedOffice.getName()+" selected");
selectedDepartment=selectedOffice.getDepartment();
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onDepartmentChanged() {
if(selectedOffice!=null)selectedSystem=selectedOffice.getDepartment();
log.info("Calling onDepartmentChanged " + ((selectedDepartment != null) ? selectedDepartment.getName() : "null"));
if(selectedDepartment != null) {
assignableRoles = roleRepo.findByDepartment(selectedDepartment);
for(int i=0;i<assignableRoles.size();i++){
System.out.println(assignableRoles.get(i));
}
} else {
assignableRoles=null;
}
}
}
What I noticed is the selectedOffice is null in the onDepartmentChanged() method, but in the onrowselect, the value is not null. I haven't progressed more than that. I have to dynamically change the roles when a department changes. Why is the selectedOffice null?
I have a datatable which has add edit delete and filter operations.
All the operations are working fine on the database but the datatable is not updating correctly after an add operation.
It is updated correctly after the 1st add operation.
when I add 2nd row the datatable is updated but the row which was added first is replaced with the row which was added 2nd but in the db they are updated correctly.
similarly when I add a 3rd row the 1st row is replaced with the 3rd row.
Software stack used in the CRUD dataTable application are :- PrimeFace 3.4.2,JSF 2.1,NetBeans 7.2.1,Java 1.6.0_37 GlassFish 3.1.x,MySql 5.x
This is my code.
**xhtml page**
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Prime Faces Data table</title>
</h:head>
<h:body>
<h:form id="form1">
<h:messages id="messages1"/>
<br/>
<p:commandButton id="Addbtn" value="Add" oncomplete="AddDialog.show()"
update=":addform"/>
<br/>
<p:dataTable id="dtusers" value="#{userdataController.retrieveData()}"
var="item"
rows="8" paginator="true" emptyMessage="No Records Found"
paginatorAlwaysVisible="false">
<p:column style="width:150px" filterMatchMode="contains"
filterBy ="#{item.id}">
<f:facet name="header"> Id </f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column style="width:150px" filterMatchMode="contains"
filterBy="#{item.name}">
<f:facet name="header"> Name </f:facet>
<h:outputText value="#{item.name}"/>
</p:column>
<p:column style="width:150px">
<p:commandButton id="editButton" update=":editform"
oncomplete="EditDialog.show()" value="Edit">
<f:setPropertyActionListener value="#{item}"
target="#{userdataController.selectedUser}"/>
</p:commandButton>
</p:column>
<p:column style="width:150px">
<p:commandButton id="deleteButton" update=":deleteform"
oncomplete="UserDialog.show()" value="Delete">
<f:setPropertyActionListener value="#{item}"
target="#{userdataController.selectedUser}"/>
</p:commandButton>
</p:column>
</p:dataTable>
</h:form>
<p:dialog header="Add User Data" resizable="false" id="AddDialog"
widgetVar="AddDialog" modal="true" showEffect="fade" hideEffect="fade"
position="center" >
<h:form id="addform">
<p:outputPanel id="AddDisplay">
<p:panelGrid columns="2" >
<f:facet name="header">
Add Userdata
</f:facet>
<h:outputLabel for="Id" value="Enter Id:"/>
<p:inputText id="Id" value="#{userdataController.selected.id}" />
<h:outputLabel for="Name" value="Enter Name:"/>
<p:inputText id="Name"
value="#{userdataController.selected.name}"/>
<p:commandButton actionListener="#{userdataController.createdata}"
update=":form1:dtusers :form1:messages1" value="Save"
oncomplete="AddDialog.hide()" style="margin:0"/>
</p:panelGrid>
</p:outputPanel>
</h:form>
</p:dialog>
//similarly dialogs for delete and edit
</h:body>
</html>
**ManagedBean**
#ManagedBean(name = "userdataController")
#SessionScoped
public class UserdataController implements Serializable {
private Userdata current;
private DataModel items = null;
#EJB
private PrimeFacesDb.session.UserdataFacade ejbFacade;
private int id;
private String name;
private Userdata SelectedUser;
public UserdataController() {
}
//getters setters for id,name and SelectedUser
private UserdataFacade getFacade() {
return ejbFacade;
}
public List retrieveData() {
List result = getFacade().findAll();
return result;
}
public void create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage("Userdata created successfully");
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Persistence Error occured");
}
}
}
the checkbox datatable of primefaces library doesn't work for me, I tried to make the same code as the showcase of primefaces but when I check some rows and I click on the view button the selectedCars[] contains 0 rows :
here is my xhtml page :
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>TODO supply a title</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable id="multiCars" var="car" value="#{fortest.mediumCarsModel}" paginator="true" rows="10"
selection="#{fortest.selectedCars}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:18px" />
<p:column headerText="id">
#{car.id}
</p:column>
<p:column headerText="date envoi">
#{car.dateEnvoi}
</p:column>
<p:column headerText="decision" >
#{car.decision}
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog id="multiDialog" header="Car Detail" widgetVar="multiCarDialog"
height="300" showEffect="fade" hideEffect="explode">
<p:dataList id="displayMulti"
value="#{fortest.selectedCars}" var="selectedCar">
id : #{selectedCar.id}, dateEnvoi #{selectedCar.dateEnvoi}
</p:dataList>
</p:dialog>
</h:form>
</h:body>
</html>
and here is my managed-Bean :
#ManagedBean
#SessionScoped
public class fortest implements Serializable {
private Commande[] selectedCars;
private dortestDataModel mediumCarsModel;
utilisateursHelper uh;
/**
* Creates a new instance of fortest
*/
public fortest() {
uh = new utilisateursHelper();
mediumCarsModel = new dortestDataModel(uh.getAllCommandes());
}
public void setSelectedCars(Commande[] selectedCars) {
System.out.println("alors je suis donc la size : "+selectedCars.length);
this.selectedCars = selectedCars;
}
public Commande[] getSelectedCars() {
return selectedCars;
}
public dortestDataModel getMediumCarsModel() {
return mediumCarsModel;
}
}
and here is my dataModel :
public class dortestDataModel extends ListDataModel<Commande> implements SelectableDataModel<Commande> {
utilisateursHelper uh;
public dortestDataModel() {
}
public dortestDataModel(List<Commande> data) {
super(data);
uh = new utilisateursHelper();
}
#Override
public Commande getRowData(String rowKey) {
//In a real app, a more efficient way like a query by rowKey should be implemented to deal with huge data
List<Commande> cars = (List<Commande>) uh.getAllCommandes();
for(Commande car : cars) {
if(car.getId().equals(rowKey))
return car;
}
return null;
}
#Override
public Object getRowKey(Commande car) {
return car.getId();
}
}
do you have any idea, thank you in advance
you forgot to attach rowCheckListener to your datatable like this
<p:ajax event="rowSelectCheckbox" listener="#{forTest.check}" />
below code is working for me. i am able to see the id and decision on the dialog.
XHTML:
i dint implement selectableDataModel, i just used rowKey attribute of datatable, you could use that as well
<h:form id="form">
<p:dataTable id="multiCars" var="car" value="#{forTest.carList}" paginator="true" rows="10"
rowKey ="#{car.id}" selection="#{forTest.selectedCars}" >
<p:ajax event="rowSelectCheckbox" listener="#{forTest.check}" />
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:18px" />
<p:column headerText="id">
#{car.id}
</p:column>
<p:column headerText="decision" >
#{car.decision}
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog id="multiDialog" header="Car Detail" widgetVar="multiCarDialog"
height="300" showEffect="fade" hideEffect="explode">
<p:dataList id="displayMulti"
value="#{forTest.selectedCars}" var="selectedCar">
id : #{selectedCar.id}, dateEnvoi #{selectedCar.decision}
</p:dataList>
</p:dialog>
</h:form>
ManagedBean:
package managedbeans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.jws.Oneway;
import org.primefaces.event.SelectEvent;
import beans.Car;
#ManagedBean(name="forTest")
#SessionScoped
public class forTest implements Serializable {
private List<Car> carList = new ArrayList<Car>();
private Car selectedCars[];
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car selectedCars[]) {
this.selectedCars = selectedCars;
}
public List<Car> getCarList() {
if(carList.size()==0) {
setCarList();
}
return carList;
}
public void setCarList() {
this.carList.add(new Car(1, "car1"));
this.carList.add(new Car(2, "car2"));
this.carList.add(new Car(3, "car3"));
}
public void check(SelectEvent event) {
System.out.println("in check");
}
}
Remove this:
<p:dialog id="multiDialog" header="Car Detail" widgetVar="multiCarDialog"
height="300" showEffect="fade" hideEffect="explode">
<p:dataList id="displayMulti"
value="#{forTest.selectedCars}" var="selectedCar">
id : #{selectedCar.id}, dateEnvoi #{selectedCar.decision}
</p:dataList>
</p:dialog>
I have a <p:dialog> with a <p:dataTable> and a <p:commandButton>.
When I add <p:columm selectionMode="multiple"> to the table, then the button doesn't invoke the action listener method. Without that column, it works fine.
How is this caused and how can I solve it?
Here is my view:
<p:dialog id="CategoriasShowPadre" header="#{msgs['Categorias.BusquedaDeCategorias']}" widgetVar="CategoriasShowPadre" modal="true">
<p:dataTable id="DTBusquedaCategoriasPadre" widgetVar="posiblesTablaP" var="BcatP" value="#{agregarCategorias.categoriasPosibles}"
emptyMessage="#{msgs['Categoria.SinRegistros']}" rowKey="#{BcatP.nombre}" selection="#{agregarCategorias.categoriasPosiblesSelecionadas}">
<p:column selectionMode="multiple" style="width:18px" />
<p:column id="nombreCol" filterBy="#{BcatP.nombre}" filterMatchMode="contains">
<f:facet name="header">
<h:outputText value="#{msgs['Categoria.ColunmnaNombre']}" />
</f:facet>
<h:outputText value="#{BcatP.nombre}" />
</p:column>
<p:column>
<f:facet name="header">
<h:outputText value="#{msgs['Categoria.ColunmnaDescripcion']}" />
</f:facet>
<h:outputText value="#{BcatP.descripcion}" />
</p:column>
</p:dataTable>
<p:commandButton id="AnadiraPadre" value="#{msgs['Categoria.Boton.AgregarCategorias']}"
immediate="true" actionListener="#{agregarCategorias.selecionadosElementosPadres()}"
onclick="CategoriasShowPadre.hide();" />
</p:dialog>
Here is the backing bean:
#ManagedBean
#RequestScoped
public class AgregarCategorias {
private List<Categorias> CategoriasPosibles;
private List<Categorias> CategoriasPosiblesSelecionadas;
#PostConstruct
private void MiPostConstructor() {
this.CategoriasPosibles = // ...
}
public List<Categorias> getCategoriasPosiblesSelecionadas() {
return CategoriasPosiblesSelecionadas;
}
public void setCategoriasPosiblesSelecionadas(List<Categorias> CategoriasPosiblesSelecionadas) {
this.CategoriasPosiblesSelecionadas = CategoriasPosiblesSelecionadas;
}
public List<Categorias> getCategoriasPosibles() {
return CategoriasPosibles;
}
public void setCategoriasPosibles(List<Categorias> CategoriasPosibles) {
this.CategoriasPosibles = CategoriasPosibles;
}
public void selecionadosElementosPadres(ActionEvent evento) {
// my method code
}
}
The 'selection' attribute of the datatable should reference an array of the domain object.
So change private List<Categoria> CategoriasPosiblesSelecionadas for private Categoria[] CategoriasPosiblesSelecionadas