I'm trying create a filter to one dataTable. I want that filter works with all keywords contained in datatable.
I am following examples at: http://www.primefaces.org/showcase/ui/data/datatable/filter.xhtml
but I can't do this works.
The problem is when I enter with any keywords the dataTable is clear showing message "No keyword found", if I delete keyword all results doesn't returns and message "No keyword found" keeps.
How can I solve this problem ?
Here how I'm trying.
XHTML
<p:dataTable id="tabelaAlunos" widgetVar="tableAlunos"
value="#{alunoMB.alunos}" var="x"
emptyMessage="No keyword found"
selectionMode="single"
selection="#{matriculaMB.aluno}"
rowKey="#{x.id}"
filteredValue="#{alunoMB.alunos}"
>
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Filtrar: " />
<p:inputText id="globalFilter"
onkeyup="PF('tableAlunos').filter()"
style="width:150px" placeholder="Filtro"/>
</p:outputPanel>
</f:facet>
<p:column headerText="Nome">
<h:outputText value="#{x.nome}"/>
</p:column>
<p:column headerText="Sobrenome">
<h:outputText value="#{x.sobreNome}"/>
</p:column>
<p:column headerText="Endereço">
<h:outputText value="#{x.endereco.endereco}"/>
</p:column>
<p:column headerText="Número">
<h:outputText value="#{x.endereco.numero}"/>
</p:column>
<p:column headerText="Cidade">
<h:outputText value="#{x.endereco.cidade}"/>
</p:column>
<p:column headerText="Bairro">
<h:outputText value="#{x.endereco.bairro}"/>
</p:column>
<p:column headerText="Unidade escolar">
<h:outputText value="#{x.unidadeEscolar.nome}"/>
</p:column>
</p:dataTable>
Managed Bean Aluno
#ManagedBean
#ViewScoped
public class AlunoMB implements Serializable{
private static final long serialVersionUID = 1L;
private Aluno bean;
private GenericDAO<Aluno> dao;
private List<Aluno> alunos = null;
private String[] sexo = {"M", "F"};
private String telefone = "";
/** persiste o objeto */
public void insert(Aluno a){
dao = new GenericDAO<Aluno>(Aluno.class);
dao.insert(a);
alunos.add(a);
bean = new Aluno();
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso" ,"Cadastro realizado com sucesso!"));
}
/** altera o objeto */
public void update(Aluno a){
dao = new GenericDAO<Aluno>(Aluno.class);
dao.update(a);
}
/** prepara para inserir o objeto */
public void prepareCreate(){
bean = new Aluno();
}
/** retorna o objeto */
public Aluno getBean() {
return bean;
}
/** define o objeto */
public void setBean(Aluno bean) {
this.bean = bean;
}
/** retorna uma lista do objeto */
public List<Aluno> getAlunos() {
if(alunos == null){
dao = new GenericDAO<Aluno>(Aluno.class);
alunos = dao.findAll();
}
return alunos;
}
/** seta uma lista do objeto */
public void setAlunos(List<Aluno> alunos) {
this.alunos = alunos;
}
Managed Bean Matricula
#ManagedBean
#ViewScoped
public class MatriculaMB implements Serializable{
private static final long serialVersionUID = 1L;
private Matricula bean = new Matricula();
private GenericDAO<Matricula> dao;
private List<Matricula> matriculas = null;
private Turma turma;
private Aluno aluno = null;
/** persiste um novo objeto */
public void insert(Matricula m){
dao = new GenericDAO<Matricula>(Matricula.class);
dao.insert(m);
matriculas.add(m);
bean = new Matricula();
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso" ,"Cadastro realizado com sucesso!"));
}
/** altera o objeto existente */
public void update(Matricula m){
dao = new GenericDAO<Matricula>(Matricula.class);
dao.update(m);
}
/** prepara para inserir uma nova matricula */
public void prepareCreate(){
bean = new Matricula();
}
/** retorna o objeto */
public Matricula getBean() {
return bean;
}
/** define o objeto */
public void setBean(Matricula bean) {
this.bean = bean;
}
/** retorna uma lista do objeto */
public List<Matricula> getMatriculas() {
dao = new GenericDAO<Matricula>(Matricula.class);
if(matriculas == null){
matriculas = dao.findAll();
}
return matriculas;
}
public Turma getTurma() {
return turma;
}
public void setTurma(Turma turma) {
this.turma = turma;
}
/** adiciona turma ao aluno */
public void addTurmaAluno(){
if(!bean.getAluno().getTurmas().contains(turma)){
bean.getAluno().addTurmas(this.turma);
}
}
public Aluno getAluno() {
return aluno;
}
public void setAluno(Aluno aluno) {
this.aluno = aluno;
bean.setAluno(this.aluno);
}
Just add a filteBy for each column.
<p:column headerText="Nome" filterBy="#{x.nome}">
<h:outputText value="#{x.nome}"/>
</p:column>
Related
I need your help in enabling and disabling inputText based on rowSelectCheckbox and rowUnselectCheckbox if the checkbox is ticked or unticked. If it is ticked, then I need to enable the inputText otherwise it should be disabled on page load and on untick. By default the inputText is disabled on the page load. Here is the code for the jsf:
<h:form id="request">
<p:dataTable value="#{dataTableView.employeeList}" id="Employee" var="emp"
selection="#{dataTableView.selectedEmployees}" rowKey="#{emp.id}">
<p:ajax event="rowSelectCheckbox" listener="#{dataTableView.EnableInputText}" />
<p:ajax event="rowUnselectCheckbox" listener="#{dataTableView.EnableInputText}" />
<p:columnGroup type="header">
<p:row>
<p:column/>
<p:column headerText="ID"/>
<p:column headerText="Name"/>
<p:column headerText="Location"/>
<p:column headerText="Remarks"/>
</p:row>
</p:columnGroup>
<p:column selectionMode="multiple" style="width:2%;text-align:center"/>
<p:column headerText="ID">
<h:outputText value="#{emp.id}"/>
</p:column>
<p:column headerText="Name">
<h:outputText value="#{emp.name}"/>
</p:column>
<p:column headerText="Location">
<h:outputText value="#{emp.location}"/>
</p:column>
<p:column headerText="Remarks">
<h:inputText id="inputT1" value="#{emp.remarks}" disabled="#{emp.disable}"/>
</p:column>
</p:dataTable>
</h:form>
And here is the code in the bean:
private List<Student> employeeList = new ArrayList<Student>();
private List<Student> selectedEmployees;
private boolean disable;
#PostConstruct
public void init() {
//add Employees
disable=true;
Student w1 = new Student(111, "AAAA", "ZZZZ", "", disable);
Student w2 = new Student(222, "CCCCC", "ZZZZZ", "OUT", disable);
Student w3 = new Student(222, "BBBBBB", "YYYYYYY", "IN", disable);
employeeList.add(w1);
employeeList.add(w2);
employeeList.add(w3);
}
public void EnableInputText(SelectEvent event) {
for(int i=0;i<=selectedEmployees.size();i++){ //Assuming you have declared as List
for(int j=0;j<=employeeList.size();j++){
if(selectedEmployees.get(i).getId().equals(employeeList.get(j).getId()))
{
employeeList.get(j).setDisable(false);
break;
}
}
}
}
The Student Bean:
public class Student {
private Integer id;
private String name;
private String location;
private String remarks;
private boolean disable;
public Student(Integer id, String name, String location, String remarks, boolean disable){
this.id = id;
this.name = name;
this.location = location;
this.remarks=remarks;
this.disable=disable;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getRemarks() {
return remarks;
}
public void setDisable(boolean disable) {
this.disable = disable;
}
public boolean isDisable() {
return disable;
}
And in the Bean, I am facing difficulties in enabling the inputText for entry if the row is ticked. So could you please help.
Now I got the error :
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 if I tick and checkbox
First thing you are using selectionMode="multiple" it means there will be multiple rows with textField enabled next
instead of this :
<h:inputText value="#{emp.remarks}" disabled="#{empBean.enable}" />
write
<h:inputText value="#{emp.remarks}" disabled="#{emp.enable}" />
means declare one variable enable in the bean itself after that:
for(int i=0;i<=selectedEmployees.size();i++){ //Assuming you have declared as List
for(int j=0;j<=empList.size();j++){
if(selectedEmployees.get(i).getId().equals(empList.get(j).getId()){
empList.get(j).setEnable(false);
}
}
}
before to this you can write one for loop and disable all the textField for list for that will work for rowUnselect
I have an entity that contain an attribute with #ElementCollection annotation. This attribute is a list of String that I add telphones(telefones). I display this telphones at a dataTable of primefaces.
How I can remove this telphone with row selected ?
I'm trying this.
Entity
#Entity
public class UnidadeEscolar implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#NotNull #Size(min=5, message="Informe o nome da unidade escolar")
#Column(unique=true)
private String nome;
private String departamento;
#Embedded
private Endereco endereco;
#ElementCollection
#JoinTable(name="telefones_ue", joinColumns=#JoinColumn(name="ue_id"))
private List<String> telefones = new ArrayList<String>();
/** adiciona telefones */
public void addTelefone(String tel){
telefones.add(tel);
}
/** remove telefone */
public void removeTelefone(int row){
telefones.remove(row);
}
Managed Bean
#ManagedBean
#ViewScoped
public class UnidadeEscolarMB implements Serializable{
private static final long serialVersionUID = 1L;
private UnidadeEscolar bean;
private GenericDAO<UnidadeEscolar> dao;
private List<UnidadeEscolar> unidades = null;
private String telefone = "";
/** add telphone to entity */
public void addTelefones(){
//System.out.println(telefone);
bean.addTelefone(telefone);
telefone = "";
}
/** remove telphone of entity */
public void removeTelefone(){
bean.getTelefones().remove(telefone);
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
xhtml
<p:tab title="Contato">
<p:fieldset legend="Telefones">
<p:dataTable id="tabelaTelefones" widgetVar="datalistTelefones"
value="#{unidadeEscolarMB.bean.telefones}" var="fone"
emptyMessage="Nenhum registro encontrado"
selectionMode="single"
selection="#{unidadeEscolarMB.telefone}"
rowKey="#{unidadeEscolarMB.bean.id}"
>
<p:column headerText="Telefone">
<h:outputText value="#{fone}"/>
</p:column>
</p:dataTable>
<p:commandButton actionListener="#{unidadeEscolarMB.removeTelefone()}" value="-" update="tabelaTelefones"/>
</p:tab>
How I can delete telphone selected at dataTable ?
I solved the problem using <f:setPropertyActionListener/>
here how I did
<p:tab title="Contato">
<p:fieldset legend="Telefones">
<p:dataTable id="tabelaTelefones" widgetVar="datalistTelefones"
value="#{unidadeEscolarMB.bean.telefones}" var="fone"
emptyMessage="Nenhum registro encontrado"
>
<p:column headerText="Telefone">
<h:outputText value="#{fone}"/>
</p:column>
<p:column headerText="">
<p:commandLink action="#{unidadeEscolarMB.removeTelefone()}" value="Excluir" update="tabelaTelefones">
<f:setPropertyActionListener target="#{unidadeEscolarMB.telefone}" value="#{fone}"/>
</p:commandLink>
</p:column>
</p:dataTable>
<p:inputMask id="telefone" widgetVar="telefoneMask" value="#{unidadeEscolarMB.telefone}" mask="(99)9-9999-9999" />
<p:commandButton actionListener="#{unidadeEscolarMB.addTelefones()}" value="+" update="telefone, tabelaTelefones"/>
<p:selectBooleanCheckbox itemLabel="Adiciona9" onchange="setMaskTelefone()" id="checkBox" widgetVar="ckbox9" value="true" immediate="true"/>
</p:fieldset>
</p:tab>
#ManagedBean
#ViewScoped
public class UnidadeEscolarMB implements Serializable{
private static final long serialVersionUID = 1L;
private UnidadeEscolar bean;
private GenericDAO<UnidadeEscolar> dao;
private List<UnidadeEscolar> unidades = null;
private String telefone = "";
/** adiciona telefone ao bean */
public void addTelefones(){
//System.out.println(telefone);
bean.addTelefone(telefone);
telefone = "";
}
/** remove telefone do bean */
public void removeTelefone(){
bean.getTelefones().remove(telefone);
telefone = "";
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
i have a datatable :
<p:dataTable id="marksTable"
var="item"
value="#{markingBean.markToEdit}"
rowKey="#{markingBean.markToEdit}"
paginator="true" rows="10"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,15"
scrollable="true"
liveScroll="true"
scrollRows="20"
emptyMessage="No details was found with given criteria">
<p:column headerText="#{bundle.labelMarkSectionOne} ">
<h:outputText value="#{item.markSectionOne}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionTwo}">
<h:outputText value="#{item.markSectionTwo}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionThree}">
<h:outputText value="#{item.markSectionThree}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionFour}">
<h:outputText value="#{item.markSectionFour}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionFive}">
<h:outputText value="#{item.markSectionFive}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionSix}">
<h:outputText value="#{item.markSectionSix}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionSeven}">
<h:outputText value="#{item.markSectionSeven}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionEight}">
<h:outputText value="#{item.markSectionEight}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionNine}">
<h:outputText value="#{item.markSectionNine}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionTen}">
<h:outputText value="#{item.markSectionTen}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionEleven}">
<h:outputText value="#{item.markSectionEleven}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionTwelve}">
<h:outputText value="#{item.markSectionTwelve}" />
</p:column>
<p:column headerText="#{bundle.labelMarkSectionThirteen}">
<h:outputText value="#{item.markSectionThirteen}" />
</p:column>
</p:dataTable>
this will only show one row, what i want to do is simply add up all these values and then take the average
how best can i do this ?
EDIT
as request
The data is retrived from a database where all values are stored, in the data table it only displays one row from the db one pre selected before hand
This is the marking bean
#Named(value = "markingBean")
#ViewScoped
//#RequestScoped
public class MarkingController {
private String searchString;
private String ordering;
private String criteria;
private String match;
private Date today;
private String caseMatch;
private Boolean changed;
//private Marking markSectionOne;
// private Marking studentNumber;
// private Marking markSectionTwo;
// private Marking markToEdit;
private int spinnerField;
private Marking markToCreate, markToEdit;
private String searchMark;
private List<Marking> userSearchResults;
private List<Marking> marksList;
private Person user;
private Progress progress;
private Marking marking;
private Boolean isCompleted;
private String disabled;
private boolean value1;
private boolean value2;
private List<String> selectedOptions;
private Integer option;
private Integer number;
private List<Marking> totalMark;
#Inject
PersonFacade personFacade;
#Inject
CohortFacade cohortFacade;
#Inject
MilestoneFacade milestoneFacade;
#Inject
ProjectFacade projectFacade;
#Inject
ProgressFacade progressFacade;
#Inject
MilestoneService milestoneService;
#Inject
MarkingFacade markingFacade;
#Inject
MarkingService markingService;
#PostConstruct
public void init() {
this.markToCreate = new Marking();
this.marking = new Marking();
this.marksList = markingFacade.findAll();
// totalMark = mark.list();
changed = false; //required otherwise will work opposite of how we want
String username = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
// Get the logged in user
List<Person> usernameSearchResults = this.personFacade.usernameSearch(FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName());
if (usernameSearchResults.size() > 0) {
this.user = usernameSearchResults.get(0);
}
String marking_id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("edit_id");
System.out.println(marking_id);
if (marking_id != null) {
this.markToEdit = this.markingFacade.find(Long.parseLong(marking_id));
}
}
public void createMarkingOne() {
System.out.println("in Create mark one");
this.markingService.createMarking(this.markToCreate);
// this.markingFacade.create(this.markToCreate);
this.setMessage(" saved");
}
public void createMarking() {
System.out.println("in Create mark");
this.markingService.createMarking(this.markToCreate);
// this.markingFacade.create(this.markToCreate);
this.setMessage(" saved");
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
/* Delete mark*/
public void deleteMark(Marking markToDelete) {
/* this.markingService.deleteMark(markToDelete);
listMarks(); //need to add the list marks function
this.setMessage("Mark has been deleted.");*/
//this.markingFacade.remove(this.marking_id);
}
// Edit existing marks
public void editMark() throws IOException {
System.out.println("in edit mark");
this.markingFacade.edit(this.markToEdit);
this.setMessage("Mark(s) for the project has been successfully been recorded.");
MarkingLog loadProp = new MarkingLog(); // re anable for testing when finished
loadProp.loadProp();
}
public void addMessage(boolean markingCompleted) {
String summary = markingCompleted ? "Checked" : "Unchecked";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(summary));
}
public void editChange() {
changed = true;
}
/**
* SEARCHES *
*/
//for the advanced search query
public void basicMarkingSearch() {
userSearchResults = markingFacade.basicMarkingSearch(searchString, criteria, ordering, match);
}
public void testMarkingSearch() {
userSearchResults = markingFacade.testMarkingSearch(searchString, ordering, match);
}
Marking entity
#Entity(name = "MARKING")
public class Marking implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
private Person marker;
#ManyToOne
private Project project;
// #ManyToOne
// private Project project;
//#ManyToMany(mappedBy = "title")
//private Project projectBeMarked;
private String markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour,
markSectionFive, markSectionSix, markSectionSeven, markSectionEight,
markSectionNine, markSectionTen, markSectionEleven, markSectionTwelve, markSectionThirteen, markAdjust, overalMark, thirdMarker, plagorism;
What i am trying to do, is add up a row markSectionOne to Thirteen and then take the average and display this to the user
I am trying to implement row selection for a datatable with primefaces, but when I click on a row, nothing displays. I've narrowed it down to the setter for the selected car is not getting called, but I do not know how to set this. Here's my code, can anybody help?
TableBean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name="TableBean")
#ViewScoped
public class ViewCDeployments implements Serializable {
private static final long serialVersionUID = 2213388781051004157L;
private final static String[] colors;
private final static String[] manufacturers;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
private List<Car> cars;
private Car selectedCar;
private Car[] selectedCars;
private CarDataModel mediumCarsModel;
public ViewCDeployments() {
cars = new ArrayList<Car>();
populateRandomCars(cars, 50);
mediumCarsModel = new CarDataModel(cars);
}
public Car[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(Car[] selectedCars) {
this.selectedCars = selectedCars;
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
private void populateRandomCars(List<Car> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
public CarDataModel getMediumCarsModel() {
return mediumCarsModel;
}
public List<Car> getCars() {
return cars;
}
}
Car.java
import java.io.Serializable;
public class Car implements Serializable {
/**
*
*/
private static final long serialVersionUID = 240545116337689611L;
private String model;
private int year;
private String manufacturer;
private String color;
private int price;
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public Car(String model, int year, String manufacturer, String color, int price) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Car))
return false;
Car compare = (Car) obj;
return compare.model.equals(this.model);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + model.hashCode();
}
#Override
public String toString() {
return "Car{" + "model=" + model + ", year=" + year + ", manufacturer=" + manufacturer + ", color=" + color + ", price=" + price + '}';
}
}
CarDataModel
import java.io.Serializable;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;
public class CarDataModel extends ListDataModel<Car> implements SelectableDataModel<Car>, Serializable {
/**
*
*/
private static final long serialVersionUID = -5147159758418722534L;
public CarDataModel() {
}
public CarDataModel(List<Car> data) {
super(data);
}
#SuppressWarnings("unchecked")
#Override
public Car 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<Car> cars = (List<Car>) getWrappedData();
for(Car car : cars) {
if(car.getModel().equals(rowKey))
return car;
}
return null;
}
#Override
public Object getRowKey(Car car) {
return car.getModel();
}
}
XHTML
<ui:composition 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"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:form id="form">
<p:dataTable id="cars" var="car" value="#{TableBean.mediumCarsModel}" paginator="true" rows="10"
selection="#{TableBean.selectedCar}">
<f:facet name="header">
RadioButton Based Selection
</f:facet>
<p:column selectionMode="single" style="width:18px" />
<p:column headerText="Model">
#{car.model}
</p:column>
<p:column headerText="Year">
#{car.year}
</p:column>
<p:column headerText="Manufacturer" >
#{car.manufacturer}
</p:column>
<p:column headerText="Color">
#{car.color}
</p:column>
<f:facet name="footer">
<p:commandButton id="viewCommand" value="View" icon="ui-icon-search"
update=":frmContent:form:displaySingle" oncomplete="singleCarDialog.show()"/>
</f:facet>
</p:dataTable>
<p:dialog id="dialog" header="Car Detail" widgetVar="singleCarDialog" resizable="false"
showEffect="fade" hideEffect="explode">
<h:panelGrid id="displaySingle" columns="2" cellpadding="4">
<f:facet name="header">
Header
</f:facet>
<h:outputText value="Model:" />
<h:outputText value="#{TableBean.selectedCar.model}" />
<h:outputText value="Year:" />
<h:outputText value="#{TableBean.selectedCar.year}" />
<h:outputText value="Manufacturer:" />
<h:outputText value="#{TableBean.selectedCar.manufacturer}" />
<h:outputText value="Color:" />
<h:outputText value="#{TableBean.selectedCar.color}" />
</h:panelGrid>
</p:dialog>
</h:form>
</ui:composition>
Just add to your datatable rowKey. Without this property selection won't work.
<p:dataTable id="cars" var="car" value="#{TableBean.mediumCarsModel}" paginator="true" rows="10" rowKey="#{car.manufacturer}" selection="#{TableBean.selectedCar}">
The rowKey must be the unique in the list of values.
I think you have added too much code.
See the example below :
test.xhml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
>
<h:head>
<title>PrimeFaces AJAX Enabled SelectOneMenu</title>
<style>
.ui-widget,.ui-widget .ui-widget {
font-size: 90% !important;
}
</style>
</h:head>
<h:body>
<h:body>
<h:form id="form">
<p:dataTable id="cars" var="car" value="#{testBean.cars}">
<p:column headerText="Model" style="width:24%">
<h:outputText value="#{car.model}" />
</p:column>
<p:column headerText="Year" style="width:24%">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Manufacturer" style="width:24%">
<h:outputText value="#{car.manufacturer}" />
</p:column>
<p:column headerText="Color" style="width:24%">
<h:outputText value="#{car.color}" />
</p:column>
<p:column style="width:4%">
<p:commandButton id="selectButton" update=":form:display"
oncomplete="carDialog.show()" icon="ui-icon-search" title="View">
<f:setPropertyActionListener value="#{car}"
target="#{testBean.selectedCar}" />
</p:commandButton>
</p:column>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="carDialog" resizable="false"
id="carDlg" showEffect="fade" hideEffect="explode" modal="true">
<h:panelGrid id="display" columns="2" cellpadding="4"
style="margin:0 auto;">
<h:outputText value="Model:" />
<h:outputText value="#{testBean.selectedCar.manufacturer}"
style="font-weight:bold" />
</h:panelGrid>
</p:dialog>
</h:form>
</h:body>
</h:body>
</html>
BackBean
package com.jmxwebapp.mbeans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean(name = "testBean")
#ViewScoped
public class CarBean {
private List<Car> cars;
private Car selectedCar;
public CarBean() {
cars = new ArrayList<Car>();
cars.add(new Car("Test", 2013, "Toyo", "Blue"));
cars.add(new Car("Test1", 2013, "Toyo", "Red"));
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
}
Car
package com.jmxwebapp.mbeans;
import java.io.Serializable;
public class Car implements Serializable {
/**
*
*/
private static final long serialVersionUID = 240545116337689611L;
private String model;
private int year;
private String manufacturer;
private String color;
private int price;
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public Car(String model, int year, String manufacturer, String color, int price) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (!(obj instanceof Car))
return false;
Car compare = (Car) obj;
return compare.model.equals(this.model);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + model.hashCode();
}
#Override
public String toString() {
return "Car{" + "model=" + model + ", year=" + year + ", manufacturer=" + manufacturer + ", color=" + color + ", price=" + price + '}';
}
}
**Try above it should work**
The problem is with dialog component. In your dialog component You're using the same object where store selected car object (selectedCar). Pages are renderized from top to bottom. Therefore when You make clic the value stored is selectedCar object from dialog component. This value is initialized in null firstly.
For this You should be other object in your dialog component.
Notice that when you are using your beans you include them "inside" the html component, like:
<p:column headerText="Model">
#{car.model}
</p:column>
When you should be incluiding the bean inside the tag in the value option:
<p:column headerText="Model" value="#{car.model}>
</p:column>
Hope it works :)
I m trying to display data in jsf datable data from the database,ans in a same row i m displaying link for Edit. Now when user will clicked on edit button then it should be inputText from outputText. Here i have done coding for that but i can't change the textbox can u please help me? Thanks in advance.
ShowData.xhtml
<h:dataTable value="#{customerdata.customerList}" var="c"
styleClass="order-table" binding="#{customerdata.dataTable}"
headerClass="order-table-header" border="1" width="100%"
rowClasses="order-table-odd-row,order-table-even-row" rows="3">
<h:column>
<h:selectBooleanCheckbox></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="heder">User ID</f:facet>
<h:inputText value="#{c.cust_id}" size="10" rendered="#{c.editable}"/>
<h:outputLabel value="#{c.cust_id}" rendered="#{not c.editable}" />
</h:column>
<h:column>
<f:facet name="heder">User Name</f:facet>
<h:inputText value="#{c.cust_name}" size="10" rendered="#{c.editable}"/>
<h:outputLabel value="#{c.cust_name}" rendered="#{not c.editable}" />
</h:column>
<h:column>
<h:commandLink value="Update" rendered="#{c.editable}" action="#{customerdata.editAction(c)}" />
<h:commandLink value="Edit" action="#{customerdata.editAction(c)}" rendered="#{not c.editable}"/>
</h:column>
<h:column>
<h:commandLink value="Delete" action="#{customerdata.deleteAction(c)}" />
</h:column>
<!-- Footer Setting -->
<f:facet name="footer">
<h:panelGroup>
<h:commandButton value="prev" action="#{customerdata.pagePrevious}"
disabled="#{customerdata.dataTable.first == 0}" />
<h:commandButton value="next" action="#{customerdata.pageNext}"
disabled="#{customerdata.dataTable.first + customerdata.dataTable.rows
>= customerdata.dataTable.rowCount}" />
</h:panelGroup>
</f:facet>
</h:dataTable>
CustomerData.java
package model;
#ManagedBean(name="customerdata")
public class CustomerData implements Serializable {
private static final long serialVersionUID = 1L;
Connection con;
Statement smt;
HtmlDataTable dataTable;
//Customer cust=new Customer();
public List<Customer> getcustomerList() throws SQLException{
//System.out.println("in getcustomerlist");
List<Customer> list= new ArrayList<Customer>();
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/openid","root","root");
smt = con.createStatement();
String query="select * from jsftable";
ResultSet rs= smt.executeQuery(query);
while(rs.next()){
Customer cust = new Customer();
cust.setCust_id(rs.getInt("cust_id"));
cust.setCust_name(rs.getString("cust_name"));
cust.setHas_attachment(rs.getBoolean("has_attachment"));
System.out.println("in cusotomer data"+cust.isEditable());
//store all data into a List
list.add(cust);
}
}
catch(Exception e){
e.printStackTrace();
}
return list;
}
public void pageFirst() {
dataTable.setFirst(0);
}
public void pagePrevious() {
dataTable.setFirst(dataTable.getFirst() - dataTable.getRows());
System.out.println("Prevoius"+dataTable.getFirst());
}
public void pageNext() {
dataTable.setFirst(dataTable.getFirst() + dataTable.getRows());
System.out.println("Next"+dataTable.getFirst());
}
public void pageLast() {
int count = dataTable.getRowCount();
int rows = dataTable.getRows();
dataTable.setFirst(count - ((count % rows != 0) ? count % rows : rows));
}
public HtmlDataTable getdataTable() {
return dataTable;
}
public void setdataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public void showRow(){
System.out.println(dataTable.getRows());
}
public String deleteAction(Customer customer) throws SQLException{
//list.remove(customer);
//System.out.println(customer.cust_id);
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/openid","root","root");
smt = con.createStatement();
String query="delete from jsftable where cust_id="+customer.cust_id+"";
//ResultSet rs= smt.executeQuery(query);
smt.executeUpdate(query);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
public String editAction(Customer customer) {
//list.remove(customer);
System.out.println(customer.cust_id);
customer.setEditable(true);
return null;
}
}
Customer.java
public class Customer {
int cust_id;
String cust_name;
boolean has_attachment;
boolean editable;
String edit_value;
public String getEdit_value() {
System.out.println("in getter");
return edit_value;
}
public void setEdit_value(String editvalue) {
this.edit_value = editvalue;
}
public boolean isHas_attachment() {
System.out.println("in getter of has_attach");
return has_attachment;
}
public void setHas_attachment(boolean hasAttachment) {
has_attachment = hasAttachment;
}
public int getCust_id() {
System.out.println("in getter of cust_id");
return cust_id;
}
public void setCust_id(int custId) {
cust_id = custId;
}
public String getCust_name() {
return cust_name;
}
public void setCust_name(String custName) {
cust_name = custName;
}
public boolean isEditable() {
//System.out.println("in isEditable"+editable);
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
//System.out.println("in set editable"+editable);
}
}
To be honest, I wonder how your code works at all. It has several major flaws.
You should start with
giving your managed bean a scope, the #ViewScoped seems the most appropriate (see here)
removing the database access from the getter method. Put it inside an #PostConstruct annotated method in your bean. Getter methods can be called several times during JSF lifecycle. The #PostConstruct method only after bean construction.
closing sql statement and connection when you are done (stmt.close() and con.close())
following bean field and method naming conventions: A private field xxx has a getter getXxx and a setter setXxx (the capitalization is important)
removing datatable binding. It is not necessary here.
I recommend to go through this simple CRUD example by BalusC and adapting it for your functional requirements.
Add id tag for datatable:
<h:dataTable value="#{customerdata.customerList}" var="c" id="customerDT"
styleClass="order-table" binding="#{customerdata.dataTable}"
headerClass="order-table-header" border="1" width="100%"
rowClasses="order-table-odd-row,order-table-even-row" rows="3">
Add in your edit CommandButton update tag:
But why you don't use the inplace component using primefaces? http://www.primefaces.org/showcase-labs/ui/inplace.jsf (need a save button)