Primefaces datatable with delete button not working - jsf

I'm trying to delete one cell with a <p:commandButton> and after i click i want to update my table. But all what happens is, that i got this Exception.
javax.persistence.EntityNotFoundException: Unable to find de.test.Datei with id 5
But in my Database i can see the facts in each table. Also when i click the button, the dates will be delete correctly. But my table doesn't update, so the cell isn't disappeared. And when i click twice, i got the above error message.
Datei.class
#Entity
public class Datei implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "DATA_ID_GENERATOR", sequenceName = "SEQ_DATA", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DATA_ID_GENERATOR")
private long id;
private String name;
private long groesse;
#Temporal(TemporalType.TIMESTAMP)
private Date datum;
#Basic(fetch = FetchType.LAZY)
#Lob
private byte[] datei;
#ManyToOne
private Benutzer benutzer;
public Benutzer getBenutzer() {
return benutzer;
}
public void setBenutzer(Benutzer benutzer) {
this.benutzer = benutzer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getGroesse() {
return groesse;
}
public void setGroesse(long groesse) {
this.groesse = groesse;
}
public byte[] getDatei() {
return datei;
}
public void setDatei(byte[] datei) {
this.datei = datei;
}
public Datei() {
// TODO Auto-generated constructor stub
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
#Override
public String toString() {
return "Datei [id=" + id + ", name=" + name + ", groesse=" + groesse
+ ", datum=" + datum + ", datei=" + Arrays.toString(datei)
+ "]";
}
}
Benutzer.class
#Entity
public class Benutzer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "CUSTOMER_ID_GENERATOR", sequenceName = "SEQ_CUSTOMER", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CUSTOMER_ID_GENERATOR")
private long id;
private String name;
private String email;
private long kundennummer;
#OneToMany(mappedBy = "benutzer", orphanRemoval = true)
private List<Datei> datei;
#Override
public String toString() {
return "Benutzer [id=" + id + ", name=" + name + ", email=" + email
+ ", kundennummer=" + kundennummer + ", datei=" + datei + "]";
}
public List<Datei> getDatei() {
return datei;
}
public void setDatei(List<Datei> datei) {
this.datei = datei;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getKundennummer() {
return kundennummer;
}
public void setKundennummer(long kundennummer) {
this.kundennummer = kundennummer;
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
}
My DateiDAO.class
[...]
public void loeschen(Datei datei, Benutzer benutzer) {
EntityManager em = emf.createEntityManager();
EntityTransaction tr = em.getTransaction();
tr.begin();
benutzer = em.merge(benutzer);
datei = em.merge(datei);
tr.commit();
benutzer.getDatei().remove(datei);
tr.begin();
em.merge(benutzer);
em.remove(em.merge(datei));
tr.commit();
}
So the only problem is, that my table dosen't update.
If i use richfaces, it works fine.
main.xhtml
<h:form id="myForm">
<p:dataTable id="dateien" var="data"
value="#{mainController.ben.datei}" rowKey="#{data.id}"
selectionMode="single" rows="5" paginator="true" rowsPerPageTemplate="5,10,15" paginatorPosition="bottom"
paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}">
<f:facet name="header">
<h:outputText value="Uploaded"/>
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{data.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{data.name}" />
</p:column>
<p:column headerText="Datum">
<h:outputText value="#{data.datum}" />
</p:column>
<p:column headerText="Delete">
<p:commandButton update="myForm"
actionListener="#{mainController.loeschen(data)}"
icon="ui-icon-trash" />
</p:column>
</p:dataTable>
</h:form>

Miss it in your process:
Delete this item from your mainController.ben.datei list after you delete item from database, and update your dataTable like Ouerghi Yassine told.
or
Get load again your data list from database on loeschen method after you delete item, its more security if you do this system and wish no have a concurrence problem.
So, you provide to your dataTable one list binding with your bean, in your case the datei list, so even if you delete item from database, this item cant be this list too.
I'm sorry for my english.

Add update="dateien" to your commandButton
<p:commandButton update="myForm"
actionListener="#{mainController.loeschen(data)}"
icon="ui-icon-trash"
update="dateien"/>

Related

p:dataTable does not update on first attempt [duplicate]

This question already has an answer here:
How and when should I load the model from database for JSF dataTable
(1 answer)
Closed 3 years ago.
I have developed a dynamic table which should refill table at every request, the same function is being performed by the code as follows:-
html
<h:form id="form">
<p:outputLabel value="Client: " />
<p:inputText id="inp" value="#{test.id}" />
<p:inputText id="inp1" value="#{test.title}" />
<p:commandButton value="Call List" action = "#{liveRangeService.LiveRangeServicesss(10)}"/>
<p:commandButton value="Call List" action = "#{liveRangeService.LiveRangeServicesss(20)}"/>
<p:dataTable var="result" id="tbl" widgetVar="dtlTBL"
value="#{liveRangeService.tableData}"
filteredValue="#{liveRangeService.filteredData}"
paginator="false"
scrollable="true" rowIndexVar="rowindex" scrollHeight="500"
scrollRows="50" liveScroll="true"
filterDelay="1100"
>
<p:ajax event="rowSelect" listener="#{test.onRowSelect(rowindex)}" />
<f:facet name="header">
<p:outputPanel layout="inline" styleClass="tabSpacer">
<h:outputText value="Global Filter:" />
<p:inputText id="globalFilter" onkeyup="PF('dtlTBL').filter()" style="width:150px;margin-left:10px;"/>
</p:outputPanel>
</f:facet>
<p:column width="50">
<f:facet name="header">
<h:outputText value="Sr." />
</f:facet>
<p:commandButton value="#{rowindex}" style="width: 49px" action="#{test.onRowSelect(rowindex)}"/>
</p:column>
<p:columns value="#{liveRangeService.tableHeaderNames}"
var="mycolHeader"
width="#{colIndex==0?'10%':colIndex==1?'70%':colIndex==2?'10%':colIndex==3?'10%':'0'}"
columnIndexVar="colIndex"
sortBy="#{result[mycolHeader]}"
filterBy="#{result[mycolHeader]}"
filterMatchMode="contains"
>
<f:facet name="header">
<h:outputText value="#{mycolHeader}" />
</f:facet>
<h:outputText value="#{result[mycolHeader]}" />
<br />
</p:columns>
</p:dataTable>
</h:form>
#ManagedBean(name="liveRangeService", eager = true)
#Dependent
public class LiveRangeService implements Serializable {
private static List< Map<String, String> > tableData;
public static List< Map<String, String> > filteredData;
private static List<String> tableHeaderNames;
private String tableColWidths;
public List<Map<String, String>> getTableData() {
return tableData;
}
public List<String> getTableHeaderNames() {
return tableHeaderNames;
}
public LiveRangeService() {
}
public static void LiveRangeServicesss(int noOfRows) {
tableData = new ArrayList< Map<String, String> >();
filteredData = new ArrayList< Map<String, String> >();
tableHeaderNames = new ArrayList<String>();
tableHeaderNames.add("ID");
tableHeaderNames.add("Title");
tableHeaderNames.add("Opn_Amt");
tableHeaderNames.add("Smr_Amt");
for (int i = 0; i < noOfRows; i++) {
Map<String, String> playlist = new HashMap<String, String>();
playlist.put("ID", "101000" + i);
playlist.put("Title", "Share Capital - Mr. " + i);
playlist.put("Opn_Amt", "0");
playlist.put("Smr_Amt", "0");
tableData.add(playlist);
}
filteredData=tableData;
System.out.println("Filled " + filteredData.size() + ", " + noOfRows);
String dlgTBL="form:tbl";
PrimeFaces.current().ajax().update(dlgTBL);
}
public String getTableColWidths() {
return tableColWidths;
}
public void setTableColWidths(String tableColWidths) {
this.tableColWidths = tableColWidths;
}
public List<Map<String, String>> getFilteredData() {
return filteredData;
}
public void setFilteredData(List<Map<String, String>> filteredData) {
this.filteredData = filteredData;
}
}
#ManagedBean(name="test")
#SessionScoped
public class Test implements Serializable {
public String id;
public String title;
public Test() {
id="1";
title="Testing";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void onRowSelect(int row) {
try {
String i="ID";
String t="Title";
String ci="id";
String ct="title";
this.getClass().getDeclaredField(ci).set(this, LiveRangeService.filteredData.get(row).get(i));
this.getClass().getDeclaredField(ct).set(this, LiveRangeService.filteredData.get(row).get(t));
PrimeFaces.current().ajax().update("form:inp");
PrimeFaces.current().ajax().update("form:inp1");
PrimeFaces.current().executeScript("PF('dlg').hide();");
} catch (Exception e) {
System.out.println("Error! " + e.getMessage() );
}
}
}
but the problem is that when the table is needed to be updated for other query, the call of function has to be done 2 times ie. i have placed two buttons, one pressing button 1, the table is populated with 10 rows and on pressing button 2, the table is populated with 20 rows. Each button is needed to be pressed two times to update the table.
Please advice.
i have just initialized the tables in Constructor, and all worked same as required.
#ManagedBean(name="liveRangeService")
#SessionScoped
public class LiveRangeService implements Serializable {
private List< Map<String, String> > tableData;
public List< Map<String, String> > filteredData;
private List<String> tableHeaderNames;
private String tableColWidths;
public List<Map<String, String>> getTableData() {
return tableData;
}
public List<String> getTableHeaderNames() {
return tableHeaderNames;
}
public LiveRangeService() {
tableData = new ArrayList< Map<String, String> >();
filteredData = new ArrayList< Map<String, String> >();
tableHeaderNames = new ArrayList<String>();
LiveRangeServicesss (-1, false);
System.out.println("in Constructor:");
}
public LiveRangeService(int noOfRows, boolean showDialogue) {
}
public void LiveRangeServicesss(int noOfRows, boolean showDialogue) {
tableData.clear();
tableHeaderNames.clear();
filteredData.clear();
tableHeaderNames.add("ID");
tableHeaderNames.add("Title");
tableHeaderNames.add("Opn_Amt");
tableHeaderNames.add("Smr_Amt");
for (int i = 0; i < noOfRows; i++) {
Map<String, String> playlist = new HashMap<String, String>();
playlist.put("ID", "101000" + noOfRows + i);
playlist.put("Title", "Share Capital - Mr. " + noOfRows + " - " + i);
playlist.put("Opn_Amt", "0");
playlist.put("Smr_Amt", "0");
tableData.add(playlist);
}
filteredData=tableData;
System.out.println("table size: " + tableData.size() + ", " + filteredData.size());
}

Passing additional Objects to commandLink

I want to use the same View for different states of a bean. Therefore I need to Inject/pass/whatever get the current bean I want to modify, but I always get null.
I already tried it with , with #Inject, and the other solutions given in How can I pass selected row to commandLink inside dataTable or ui:repeat?
The View:
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import org.primefaces.PrimeFaces;
import de.auticon.beans.Mitarbeiter;
import de.auticon.beans.Skill;
#Named(value = "skillView")
#ViewScoped
public class SkillView implements Serializable {
private static final long serialVersionUID = -3256509521249071048L;
private Mitarbeiter employee;
private Skill skill = new Skill();
private List<String> expertises = new ArrayList<String>();
#PostConstruct
public void init() {
List<Expertise_String> expertiseObjects = Queries.findAllExpertises();
for (Expertise_String singleExpertise : expertiseObjects) {
expertises.add(singleExpertise.getExpertise() + " - " + singleExpertise.getFullNameString());
}
}
//Here employee is null, but I need the new/existing employee
public void addSkill() {
employee.getSkills().add(skill);
PrimeFaces.current().dialog().closeDynamic(null);
}
public void closeDialog() {
PrimeFaces.current().dialog().closeDynamic(null);
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
public Mitarbeiter getEmployee() {
return employee;
}
public void setEmployee(Mitarbeiter employee) {
this.employee = employee;
}
}
XHTML from which it is called for existing employees:
<h:form id="form">
<p:panelGrid columns="2" styleClass="ui-noborder">
<p:menu toggleable="true">
<p:submenu label="Verwaltung">
<p:menuitem>
<p:commandButton value="Mitarbeiter anlegen" action="#{adminView.addNewEmployee}" icon="pi pi-users"
process="#this :form:skillsDialog">
<p:ajax event="dialogReturn" listener="#{mitarbeiterView.update}" update=":form, :form:table"/>
</p:commandButton>
</p:menuitem>
</p:submenu>
</p:menu>
<p:dataTable id="table" var="row" value="#{mitarbeiterView.mitarbeiter}" liveResize="true" resizableColumns="true">
<p:column headerText="Skillset">
<p:commandLink update=":form:skillsDialog, :form:skillsDetails" oncomplete="PF('skillsDialog').show()" title="Detail"
styleClass="ui-icon pi pi-search">
<f:setPropertyActionListener value="#{row}" target="#{mitarbeiterView.selectedEmployee}" />
</p:commandLink>
<p:commandLink action="#{adminView.openNewSkillDialog(row)}" title="add" styleClass="ui-icon pi pi-plus">
<!-- <f:setPropertyActionListener value="#{row}" target="#{skillView.employee}" /> -->
</p:commandLink>
</p:column>
</p:dataTable>
</p:panelGrid>
<p:dialog id="skillsDialog" header="Skillsheet von #{mitarbeiterView.selectedEmployee.vorname} #{mitarbeiterView.selectedEmployee.name}"
showEffect="fade" widgetVar="skillsDialog" modal="true" resizable="true">
<p:outputPanel id="skillsDetails">
<p:dataTable var="skillRow" value="#{mitarbeiterView.selectedEmployee.skills}">
<p:column headerText="Skill">
<h:outputText value="#{skillRow.name}" />
</p:column>
<p:column headerText="Ausprägung">
<h:outputText value="#{skillRow.expertise} - #{skillRow.expertiseString.fullName}" />
</p:column>
<p:column headerText="Beschreibung">
<h:outputText value="#{skillRow.description}" />
</p:column>
</p:dataTable>
</p:outputPanel>
</p:dialog>
</h:form>
Second XHTML, for new employees:
<h:form id="newForm">
<h3>Skillsheet</h3>
<p:panelGrid id="skillPanel" columns="2" cellpadding="5" styleClass="ui-noborder">
<p:column style="width:50px">
<p:commandButton id="openAddSkill" process="#this" action="#{adminView.openNewSkillDialog}"
title="Neuer Skill" icon="pi pi-plus">
<!-- <f:setPropertyActionListener target="#{skillView.employee}" value="#{newEmployeeView.newEmployee}"/> -->
<p:ajax event="dialogReturn" update=":newForm :newForm:skillPanel"/>
</p:commandButton>
</p:column>
</p:panelGrid>
<p:commandButton value="Hinzufügen" id="addSkill" icon="pi pi-plus" action="#{skillView.addSkill()}"/>
</h:form>
AdminView.java:
#Named(value = "adminView")
#ViewScoped
public class AdminView implements Serializable {
private static final long serialVersionUID = 5252224062484767900L;
#Inject
private SkillView skillView;
public void addNewEmployee() {
Map<String, Object> options = new HashMap<String, Object>();
options.put("id", "newEmployeeDialogID");
options.put("widgetVar", "newEmployeeDialogVar");
options.put("resizable", false);
options.put("modal", false);
PrimeFaces.current().dialog().openDynamic("/dialogs/newEmployee", options, null);
}
public void openNewSkillDialog(Mitarbeiter employee) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("resizable", true);
options.put("modal", false);
options.put("contentWidth", 420);
PrimeFaces.current().dialog().openDynamic("/dialogs/skill", options, null);
skillView.setEmployee(employee);
}
}
Skill.java:
public class Skill {
#NotNull(message = "Skill fehlt")
private String name;
#NotNull(message = "Bitte Ausprägung angeben")
private short expertise;
private String description;
private String expertiseFullname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public short getExpertise() {
return expertise;
}
public void setExpertise(short expertise) {
this.expertise = expertise;
}
public String getExpertiseFullname() {
return expertiseFullname;
}
public void setExpertiseFullname(String expertiseFullname) {
this.expertiseFullname = expertiseFullname;
}
public void setExpertise(String fullName) {
try {
this.expertise = Short.valueOf(fullName.substring(0, fullName.indexOf(" - ")));
} catch (Exception e) {
this.expertise = 0;
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Mitarbeiter.java:
public class Mitarbeiter {
private int id;
#NotNull(message = "Nachname fehlt")
private String name;
#NotNull(message = "Vorname fehlt")
private String vorname;
private Date entryDate;
private List<Skill> skills = new ArrayList<Skill>();
private int expertise;
public Mitarbeiter() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public List<Skill> getSkills() {
return skills;
}
public void setSkills(List<Skill> skills) {
this.skills = skills;
}
public int getExpertise() {
return expertise;
}
public void setExpertise(int expertise) {
this.expertise = expertise;
}
MitarbeiterView.java:
#Named(value = "mitarbeiterView")
#ViewScoped
public class MitarbeiterView implements Serializable {
private static final long serialVersionUID = 7924178697538784022L;
#Inject
MitarbeiterService mitarbeiterService;
private List<Mitarbeiter> mitarbeiter;
private Mitarbeiter selectedEmployee;
#PostConstruct
public void init() {
SessionConfig.initSession();
new Commons();
updateMitarbeiter();
}
private void updateMitarbeiter() {
mitarbeiter = new ArrayList<Mitarbeiter>();
List<EmployeeDTO> dtos = Queries.findAllEmployees();
for (EmployeeDTO employeeDTO : dtos) {
mitarbeiter.add(mitarbeiterService.convertToMitarbeiter(employeeDTO));
}
}
public void update() {
updateMitarbeiter();
PrimeFaces.current().ajax().update("form:table");
}
public List<Mitarbeiter> getMitarbeiter() {
return mitarbeiter;
}
public void setMitarbeiter(List<Mitarbeiter> mitarbeiter) {
this.mitarbeiter = mitarbeiter;
}
public void setSelectedEmployee(Mitarbeiter selectedEmployee) {
this.selectedEmployee = selectedEmployee;
}
public Mitarbeiter getSelectedEmployee() {
return selectedEmployee;
}
NewEmployeeView.java:
#Named(value = "newEmployeeView")
#ViewScoped
public class NewEmployeeView implements Serializable {
private static final long serialVersionUID = 789108010781037452L;
#ManagedProperty(value = "#{mitarbeiter}")
private Mitarbeiter newEmployee = new Mitarbeiter();
#PostConstruct
public void init() {
}
public Mitarbeiter getNewEmployee() {
return newEmployee;
}
public void setNewEmployee(Mitarbeiter mitarbeiter) {
this.newEmployee = mitarbeiter;
}
Calling adSkill() from the first XHTML should have the selected employee from the Datatable. In the second case, it should have a freshly created, "empty" employee, which I already provide.
I think that major cause of your problems is that skillView bean is #RequestScoped meaning that it is being constructed and destroyed on each request and thus your employee is being reinitialized/reset to null every time. Check out this accepted answer for details.
Hints that might lead you to solution:
put debug lines in at least init() and setEmployee(..) methods of skillView and observe behaviour,
change scope of skillView to #ViewScoped which will preserve employee object across multiple Ajax requests

Fill datatable from database in jpa [duplicate]

This question already has answers here:
Showing Hibernate/JPA results in JSF datatable causes: java.lang.NumberFormatException: For input string: "[propertyname]"
(2 answers)
Closed 7 years ago.
public List<MemberEntity> getMember() {
EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("PrimeEclipseLink");
EntityManager entityManager = entityManagerFactory
.createEntityManager();
Query query = entityManager
.createNativeQuery("Select * FROM member");
memberEntities = (List<MemberEntity>)query.getResultList();
return memberEntities;
}
I want to fill my databable from database.but it doesnt work please help me:) when I click list button the table fill like picture.by the way,my database contains 3 records.thats why 3 zero.
xhtml page is here.
<h:form id="member">
<p:dataTable var="members" value="#{mainScreen.memberEntities}">
<p:column headerText="name">
<h:outputText value="#{memberEntity.name}" />
</p:column>
<p:column headerText="surname">
<h:outputText value="#{memberEntity.surname}" />
</p:column>
<p:column headerText="fathername">
<h:outputText value="#{memberEntity.fathername}" />
</p:column>
<p:column headerText="age">
<h:outputText value="#{memberEntity.age}" />
</p:column>
<p:column headerText="email">
<h:outputText value="#{memberEntity.email}" />
</p:column>
<p:column headerText="username">
<h:outputText value="#{memberEntity.username}" />
</p:column>
<p:column headerText="password">
<h:outputText value="#{memberEntity.password}" />
</p:column>
</p:dataTable>
</h:form>
` #ManagedBean
#Entity
#Table(name = "member")
public class MemberEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int memberid;
private int age;
private String name;
private String surname;
private String fathername;
private String email;
private String username;
private String password;
public MemberEntity(int memberid, int age, String name, String surname,
String fathername, String email, String username, String password) {
super();
this.memberid = memberid;
this.age = age;
this.name = name;
this.surname = surname;
this.fathername = fathername;
this.email = email;
this.username = username;
this.password = password;
}
public MemberEntity() {
super();
// TODO Auto-generated constructor stub
}
public int getMemberid() {
return memberid;
}
public void setMemberid(int memberid) {
this.memberid = memberid;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getFathername() {
return fathername;
}
public void setFathername(String fathername) {
this.fathername = fathername;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "Member [memberid=" + memberid + ",name=" + name + ",surname="
+ surname + ",age=" + age + ",email=" + email + ",fathername="
+ fathername + ",username=" + username + ",password="
+ password + "]";
}
}
In your p:dataTable the var attribute is named membres, while in the p:column values you are using memberEntity, so you have to change it to members.
From:
<p:column headerText="name">
<h:outputText value="#{memberEntity.name}" />
</p:column>
To:
<p:column headerText="name">
<h:outputText value="#{members.name}" />
</p:column>
I found solution. in getMember() method instead of createNativeQuery("Select * FROM member") true---> createNativeQuery("Select * FROM members,MemberEntity.class)

primefaces not show dataTable values with lazyModel

I'm starting with primefaces and I try use LazyModel in p:dataTable.
I already implemented the LazyModel, bean and jsf. The call's to bean and model occur's correctly and my bean return a list with elements, but my jsf show nothing.
Please, somebody know whats happen?
Bellow is my code:
JSF:
<ui:composition template="./newTemplate.xhtml">
<ui:define name="content">
content
<h:form>
<p:panel id="formFiltro">
<p:messages id="messages"/>
<h:panelGrid>
<h:outputLabel for="fieldConta" value="Número da Conta:"/>
<p:inputText id="fieldConta" value="#{log.nrConta}" label="Número da Conta">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldConta" />-->
<h:outputLabel for="fieldAgencia" value="Código da Agência:"/>
<p:inputText id="fieldAgencia" value="#{log.nrAgencia}" label="Código da Agência">
<f:convertNumber integerOnly="true" type="number"/>
</p:inputText>
<!--<p:message for="fieldAgencia" />-->
<center>
<p:commandButton ajax="false" value="Pesquisar" action="#{log.search}" />
</center>
</h:panelGrid>
</p:panel>
<p:dataTable var="l" value="#{log.lazyLogModel}" paginator="true" rows="5"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" id="logTable" lazy="true">
<p:column headerText="ID">
<h:outputText value="#{l.logId}" />
</p:column>
<p:column headerText="Agência">
<h:outputText value="#{l.logAgencia}" />
</p:column>
<p:column headerText="Conta">
<h:outputText value="#{l.logConta}" />
</p:column>
<p:column headerText="SO">
<h:outputText value="#{l.logSo}" />
</p:column>
<p:column headerText="Plugin">
<h:outputText value="#{l.logVersaoPlugin}" />
</p:column>
<p:column headerText="Tam F10">
<h:outputText value="#{l.logTamF10}" />
</p:column>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
My bean:
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
#PostConstruct
public void init()
{
this.lazyLogModel = new LazyLogModel();
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel getLazyLogModel()
{
return this.lazyLogModel;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}
My LazyModel:
public class LazyLogModel extends LazyDataModel<TbLogLog> {
private String nrConta;
private String cdAgencia;
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
/**
* #return the nrConta
*/
public String getNrConta() {
return nrConta;
}
/**
* #param nrConta the nrConta to set
*/
public void setNrConta(String nrConta) {
this.nrConta = nrConta;
}
/**
* #return the cdAgencia
*/
public String getCdAgencia() {
return cdAgencia;
}
/**
* #param cdAgencia the cdAgencia to set
*/
public void setCdAgencia(String cdAgencia) {
this.cdAgencia = cdAgencia;
}
}
Consult Method called by LazyModel:
private List<TbLogLog> getListLog(String hql, int firstResult, int sizePage) throws Exception {
List resultList = null;
try {
Session session = HubernateUtil.getSessionFactory().openSession();
if ((hql == null) || (hql.trim().length() == 0)) {
hql = QUERY_PESQUISAR_TODOS;
}
Query q = session.createQuery(hql);
if(firstResult > 0 )
q.setFirstResult(firstResult);
if(sizePage > 0)
q.setMaxResults(sizePage);
resultList = q.list();
} catch (HibernateException he) {
he.printStackTrace();
}
return resultList;
}
Everything work's fine, but my jsf don't show any result.
Thanks in advance.
Remove the init() in consultaJsf Class and update the getLazyLogModel() as follows
#ManagedBean(name="log")
#RequestScoped
public class consultaJsf implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Creates a new instance of consultaJsf
*/
private List<TbLogLog> listaLog;
private LazyLogModel<TbLogLog> lazyLogModel;
private int nrConta;
private int nrAgencia;
public consultaJsf() {
try{
//this.listaLog = new ConsultarDados().getListLogAll();
}catch(Exception e){
e.printStackTrace();
}
}
public List<TbLogLog> getListaLog()
{
return listaLog;
}
public int getNrConta()
{
return nrConta;
}
public void setNrConta(int nrConta)
{
this.nrConta = nrConta;
}
public int getNrAgencia()
{
return nrAgencia;
}
public void setNrAgencia(int nrAgencia)
{
this.nrAgencia = nrAgencia;
}
public LazyLogModel<TbLogLog> getLazyLogModel()
{
if (lazyLogModel== null) {
lazyLogModel= new LazyDataModel<TbLogLog>() {
#Override
public List<TbLogLog> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, String> filters) {
List<TbLogLog> listaLog = null;
try{
listaLog = new ConsultarDados().getListLogAll(first, pageSize);
}catch(Exception e){
return null;
}
return listaLog;
}
};
}
return listaLog;
}
public String search() throws Exception
{
if(nrConta != 0)
this.listaLog = new ConsultarDados().getListLogByConta(nrConta);
else if(nrAgencia != 0)
this.listaLog = new ConsultarDados().getListLogByAgencia(nrAgencia);
return null;
}
}

How can I use multiple value in Input text field JSF

In my xhtml there are 3 input field which calculate remaining day of two <p:calendar> dates. In next step I want to store calculated remaining day to MY DB.
<p:dataTable styleClass="vtable" editable="true" var="user"
editMode="cell" value="#{userBean.employeeList}">
<p:column styleClass="columntd" headerText="#{text['user.startedDate']}">
<p:calendar widgetVar="fromCal" value="#{vacationBean.vacation.beginDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.fromSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['user.finishedDate']}">
<p:calendar widgetVar="toCal" value="#{vacationBean.vacation.endDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.toSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['employee.remainingdays']}">
<p:inputText id="diff" styleClass="daysNumber"
value="#{dayDiffBean.diff}" />
</p:column>
</p:dataTable>
<h:commandButton styleClass="sndbutton1"
value="#{text['employee.send']}" action="#{vacationBean.addVac}"/>
I used value="#{dayDiffBean.diff} to get remaining day and now I also want to use my vacationbean to store remaingday to my db using like this : value="#{vacationBean.vacation.balanceDay}"
But I cant use 2 value in inputtext field like this:
<p:inputText value="dayDiffBean.diff" value1="vacationBean.vacation.balanceDay">
How can i solve this problem?
This is my vacation bean code:
#ManagedBean(name="vacationBean")
#ViewScoped
public class VacationBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Date vEndDate;
private boolean selected;
private Date vStartDate;
private Date createdDate;
private String isNobody;
Requestrelax vacation;
Employee e;
Calendar javaCalendar = null;
private short balanceDay;
#EJB
VacationLocal vacations;
#ManagedProperty(value="#{loginBean.userId}")
Integer userId;
#EJB
EmployeesLocal employees;
#PostConstruct
public void init(){
System.out.println("0");
//System.out.println("STATrtsg >> . "+ diff.getDiff());
vacation=new Requestrelax();
e=employees.getEmployee(userId);
vacation.setEmployee(e);
System.out.println("balanday is:"+balanceDay);
}
public void addVac(){
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
vacations.addEmployeeVacation(vacation);
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Employee getE() {
return e;
}
public void setE(Employee e) {
this.e = e;
}
public Requestrelax getVacation() {
return vacation;
}
public void setVacation(Requestrelax vacation) {
this.vacation = vacation;
}
public Date getvEndDate() {
return vEndDate;
}
public void setvEndDate(Date vEndDate) {
this.vEndDate = vEndDate;
}
public Date getvStartDate() {
return vStartDate;
}
public void setvStartDate(Date vStartDate) {
this.vStartDate = vStartDate;
}
public short getBalanceDay() {
return balanceDay;
}
public void setBalanceDay(short balanceDay) {
this.balanceDay = balanceDay;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getIsNobody() {
return isNobody;
}
public void setIsNobody(String isNobody) {
this.isNobody = isNobody;
}
}
And daydiffbean code :
#ManagedBean(name="dayDiffBean")
#SessionScoped
public class DayDiffBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Date from;
private Date to;
private String diff="";
private final long oneDay=1000*60*60*24;
public void fromSelected(SelectEvent event){
from=(Date) event.getObject();
calDiff();
}
public void toSelected(SelectEvent event){
to=(Date) event.getObject();
calDiff();
}
public void calDiff(){
if(from==null||to==null){
diff="N/A";
return;
}
diff=(to.getTime()-from.getTime())/oneDay+"";
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getFrom() {
return from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
}
From the code, one way to add balanceDay to your vacationBean is by passing the diff string as a parameter to addVac() method (notice action in the second line):
<h:commandButton styleClass="sndbutton1" value="#{text['employee.send']}"
action="#{vacationBean.addVac(dayDiffBean.diff)}"/>
Then, for your VacationBean.addVac():
// 'diff' is now being passed in as a parameter
public void addVac(String diff) {
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
// UPDATED
// so now you can set balanceDay
setBalanceDay(Short.parseShort(diff));
vacations.addEmployeeVacation(vacation);
}

Resources