PrimeFaces SelectOneRadio - primefaces

I have one req , where I have a datable , which has x columns. One column contains 3 radio buttons .Which i am able to display . But my problem is I want one radio button to be selected by default .
What I am doing : On Load of datatable i am creating one variable (also i tried with SlectIte list) , but unable to get checked value.
Can anyone provide a simple working example?

This is my demonstration which present how to default radio value in datatable
XHTML
<h:form>
<p:dataTable var="catalog" value="#{radioView.catalogs}">
<p:column headerText="City">
<p:selectOneRadio id="city"
value="#{catalog.city}"
columns="3">
<f:selectItems value="#{radioView.cities}"
var="c"
itemLabel="#{city}"
itemValue="#{city}"/>
</p:selectOneRadio>
</p:column>
</p:dataTable>
<p:commandButton value="changeSelection"
process="#form"
update="#form"
actionListener="#{radioView.changeSelection}"/>
<p:commandButton value="submit"
process="#form"
update="#form"
actionListener="#{radioView.submit}"/>
</h:form>
ManagedBean
#ManagedBean
public class RadioView {
private List<Catalog> catalogs;
private List<String> cities;
#PostConstruct
public void init() {
cities = new ArrayList<String>();
cities.add("San Francisco");
cities.add("London");
cities.add("Paris");
//default radio value
Catalog c1 = new Catalog("San Francisco");
Catalog c2 = new Catalog("London");
Catalog c3 = new Catalog("Paris");
Catalog c4 = new Catalog("London");
catalogs = new ArrayList<Catalog>();
catalogs.add(c1);
catalogs.add(c2);
catalogs.add(c3);
catalogs.add(c4);
}
public List<Catalog> getCatalogs() {
return catalogs;
}
public void setCatalogs(List<Catalog> catalogs) {
this.catalogs = catalogs;
}
public List<String> getCities() {
return cities;
}
public void changeSelection(ActionEvent event){
for (Catalog catalog : catalogs) {
catalog.setCity("San Francisco");
}
}
public void submit(ActionEvent event) {
for (Catalog catalog : catalogs) {
System.out.println(catalog.getCity());
}
}
}
Domain
public class Catalog implements Serializable{
private String city;
public Catalog(String city){
this.city = city;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

Related

getting null value from inputtext field and comandbutton not invoked action method in primefaces

<h:form> <p:inputText id="uname" value="#{user.name}"/>
<p:inputText id="ac" value="#{user.account}"/>
<p:commandButton id="submit1" value="Submit" action="#{user.commandButtonAction}" /> ​
</h:form>
this is xhtml main code
backingbean is used managedbean and viewscoped annotation
#ManagedBean(name="user")
#ViewScoped
public class user {
private String account;
private String name;
public String getName() {
System.out.println(" name is ::"+ name);
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
System.out.println("account no is:: "+ account);
return account;
}
}
public void setAccount(String account) {
this.account = account;
}
public void commandButtonAction() throws IOException{
System.out.println("succesful");
}

PrimeFaces DataTable not displaying anything, as backing bean's methods are not called at all

I have a problem similar to the ones described here:
primefaces datatable not displaying anything
PrimeFaces DataTable "No records found" when there are records
my PrimeFaces datatable does not show any results, altough there are records in the database. Moreover: it seems that NO JAVA method is called when I request the page from the browser - at least the init() method of the backing bean seems not to be called at all
Where can the problem be? I would appreciate any help!
Thank you!
My template:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Bibliothek - Customers </title>
</h:head>
<h:body>
<h:form id="customersform">
<p:growl id="growl" life="2000" />
<p:panel header="All customers in the application" />
<p:dataTable id="customersTable" var="customer"
value="#{kundenBean.dataModel}" paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
resizableColumns="true" rowsPerPageTemplate="5,10,15"
selection="#{kundenBean.selektierterKunde}" selectionMode="single"
rowKey="#{customer.id}" lazy="true">
<p:column headerText="Customer's Name" style="width:332px;text-align:center"
sortBy="#{customer.vorname}" filterBy="#{customer.vorname}">
<h:outputText value="#{customer.vorname}" />
</p:column>
<p:column headerText="Customer's Address" sortBy="#{customer.adresse}"
filterBy="#{customer.adresse}">
<h:outputText value="#{customer.adresse}" />
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
The Backing Bean:
#Named
#ViewScoped
public class KundenBean {
private Logger logger = Logger.getLogger(KundenBean.class.getName());
public static final String SELECTED_CUSTOMER = "selectedCustomer";
#Inject
private KundeDBService kundenDBService;
private LazyKundeDataModel dataModel;
private Kunde selektierterKunde;
private int selectedCustId;
#PostConstruct
private void init() {
this.dataModel = new LazyKundeDataModel(kundenDBService);
}
public LazyKundeDataModel getDataModel() {
return dataModel;
}
public void setDataModel(LazyKundeDataModel dataModel) {
this.dataModel = dataModel;
}
public Kunde getSelektierterKunde() {
return selektierterKunde;
}
public int getSelectedCustId() {
return selectedCustId;
}
public void setSelektierterKunde(Kunde selektierterKunde) {
this.selektierterKunde = selektierterKunde;
}
public void onRowSelect(SelectEvent event) {
selectedCustId = ((Kunde) event.getObject()).getId();
}
public void onRowDblClick(final SelectEvent event) {
selectedCustId = ((Kunde) event.getObject()).getId();
try {
ExternalContext extCtx = FacesContext.getCurrentInstance()
.getExternalContext();
extCtx.getFlash().put(SELECTED_CUSTOMER,((Kunde) event.getObject()));
FacesContext.getCurrentInstance().getExternalContext().redirect("rents.xhtml?custId=" +selectedCustId);
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
}
}
}
The Data Model:
public class LazyKundeDataModel extends LazyDataModel<Kunde> {
private static final long serialVersionUID = 1L;
private KundeDBService kundeDBService;
public LazyKundeDataModel(KundeDBService kundeDBService) {
this.kundeDBService = kundeDBService;
}
#Override
public Kunde getRowData(String rowKey) {
return kundeDBService.getKundeById(Integer.valueOf(rowKey));
}
#Override
public Object getRowKey(Kunde kunde) {
return kunde.getId();
}
#Override
public List<Kunde> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
List result = this.kundeDBService.load(first, pageSize, sortField, sortOrder, filters);
// rowCount
this.setRowCount(result.size());
this.setPageSize(pageSize);
return result;
}
}
The DB Service:
#Stateless
public class KundeDBService {
#PersistenceContext
private EntityManager em;
public static final String JOINING_OR = " OR ";
public static final String JOINING_AND = " AND ";
public static final String CONDITION_WHERE = " WHERE ";
private static Logger logger = Logger.getLogger(KundeDBService.class.getName());
public List<? extends Kunde> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
List<? extends Kunde> result = new ArrayList<Kunde>();
String selectQUERY = " select k from Kunde k ";
if (filters.size() > 0) {
selectQUERY += addFiltersToQuery(filters);
}
if (sortField != null) {
selectQUERY += " order by k." + sortField;
if (sortOrder != null) {
selectQUERY += " " + (sortOrder);
}
}else { // sortField == null, default sort by customer's name
selectQUERY += " order by k.vorname asc";
}
Query emQuery = em.createQuery(selectQUERY);
emQuery.setFirstResult(first);
emQuery.setMaxResults(pageSize);
result = (List<Kunde>) emQuery.getResultList();
return result;
}
private String addFiltersToQuery(Map<String, Object> filters) {
if (filters.size() == 0)
return StringUtils.EMPTY;
StringBuilder whereCondition = new StringBuilder(CONDITION_WHERE);
int pseudoCounter = 0;
for (Entry<String, Object> entry : filters.entrySet()) {
whereCondition.append("k." + entry.getKey() + " LIKE :" + "x" + (++pseudoCounter));
whereCondition.append(JOINING_AND);
}
if (whereCondition.length() > CONDITION_WHERE.length()) {
whereCondition.delete(whereCondition.length() - JOINING_AND.length(), whereCondition.length());
}
return whereCondition.toString();
}
public Kunde getKundeById(int id) {
return em.find(Kunde.class, Integer.valueOf(id));
}
}
I solved the problem by replacing the annotation #Named by the annotation javax.faces.bean.ManagedBean on the KundenBean class. I am not sure what exactly the problem was, but I suppose that it has something to do with the problem outlined here
JSF View Scoped Bean Reconstructed Multiple Times
So, now the changed and working KundenBean class looks like this:
#ManagedBean (name = "kundenBean")
#ViewScoped
public class KundenBean {
//rest of the lines unchanged

Primefaces DataTable CellEdit not updating outputLabel

I've actually found quite a bit on this in various different forums, but none of them appear to have worked for me. My problem isn't even that complicated, but I can't figure out why it's not working. I've set up my datatable so that it's editable and set the editMode="cell". I set up the ajax event and it fires, but the new and old values are always null.
When I'm finished editing a cell and go to the next cell, the cell goes back to the old value. When I click back into it, it shows the new value. Both the outputLabel and inputText tags use the exact same variable, but they are not showing the same value. I've tried manually updating the table manually through the method call as well and that does nothing. Also tried putting a p:ajax tag inside the inputText tag to update the table and that didn't work either.
Here's my JSF code:
<p:dataTable id="dynamicTable" value="#{column.values}" var="value" editable="true" editMode="cell">
<p:ajax event="cellEdit" listener="bean.updateCell" immediate="true" update=":dynamicTable"/>
<p:columns value="#{bean.columns}" var="column">
<f:facet name="header">
<p:outputLabel value="#{column.name}"/>
</f:facet>
<p:cellEditor>
<f:facet name="output"><p:outputLabel value="#{value}"/></f:facet>
<f:facet name="input"><p:inputText value="#{value}"/></f:facet>
</p:cellEditor>
</p:columns>
</p:dataTable>
Here's my bean:
#ManagedBean(name = "bean")
#ViewScoped
public class Bean implements Serializable {
private ArrayList<Column> columns;
public ArrayList<Column> getColumns(){
return columns;
}
public void setColumns(ArrayList<Column> columns){
this.columns = columns;
}
#PostConstruct
void init(){
columns = new ArrayList<>();
Column column = new Column();
column.setName("Acronym");
ArrayList<String> values = new ArrayList<>();
values.add("KFC");
values.add("TTYL");
values.add("BRB");
column.setValues(values);
columns.add(column);
column = new Column();
column.setName("Meaning");
values = new ArrayList<>();
values.add("Kentuky Fried Chicken");
values.add("Talk to you later");
values.add("Be right back");
column.setValues(values);
columns.add(column);
}
public void updateCell(CellEditEvent event){
System.out.println((String) event.getNewValue();
}
}
And my Column class:
public class Column{
private ArrayList<String> values;
private String name;
public ArrayList<String> getValues(){
return values;
}
public void setValues(ArrayList<String> values){
this.values = values;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
I rewrote the code to not include sensitive information and renamed variables, so if I'm missing something it's possible that I already have it in my code, but have accidentally removed it.
It turns out the way I was doing the p:columns tag was incorrect. After I made the following changes my problem was solved.
I've made an additional class called TableRow with various String objects to signify the columns to be used. Here's the new code:
JSF:
<p:dataTable id="dynamicTable" value="#{bean.tblRows}" var="row" editable="true" editMode="cell">
<p:columns value="#{bean.columns}" var="column">
<f:facet name="header">
<p:outputLabel value="#{column.name}"/>
</f:facet>
<p:cellEditor>
<f:facet name="output"><p:outputLabel value="#{row[column.variable]}"/></f:facet>
<f:facet name="output"><p:inputText value="#{row[column.variable]}"/></f:facet>
</p:cellEditor>
</p:columns>
</p:dataTable>
Bean:
#ManagedBean (name = "bean")
#ViewScoped
public class Bean implements Serializable {
private ArrayList<TableRow> tblRows;
private ArrayList<Column> columns;
public ArrayList<TableRow> getTblRows(){
return tblRows;
}
public void setTblRows(ArrayList<TableRow> tblRows){
this.tblRows = tblRows;
}
public ArrayList<Column> getColumns(){
return columns;
}
public void setColumns(ArrayList<Column> columns){
this.columns = columns;
}
#PostConstruct
void init(){
columns = new ArrayList<>();
columns.add(new Column("Acronym", "col1");
columns.add(new Column("Meaning", "col2");
tblRows = new ArrayList<>();
tblRows.add(new TableRow("KFC", "Kentuky Fried Chicken"));
tblRows.add(new TableRow("TTYL", "Talk to you later"));
tblRows.add(new TableRow("BRB", "Be right back"));
}
}
TableRow Class:
public class TableRow {
private String col1;
private String col2;
public TableRow(String col1, String col2){
this.col1 = col1;
this.col2 = col2;
}
public String getCol1(){
return col1;
}
public void setCol1(String col1){
this.col1 = col1;
}
public String getCol2(){
return col2;
}
public void setCol2(String col2){
this.col2 = col2;
}
}
Column Class:
public class Column {
private String name;
private String variable;
public Column(String name, String variable){
this.name = name;
this.variable = variable;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getVariable(){
return variable;
}
public void setVariable(String variable){
this.variable = variable;
}
}
The reason why I did "col1" and "col2" instead of give distinct variable names is that the user can choose the column header names so I won't know what to name the variables ahead of time. I was wondering if anyone would like to enlighten me how I could handle this dynamically a little better. When the bean is initialized I don't know how many columns there are going to be or what the column names are going to be.

Open details of a single row in a datatable in a new page

I have a datatable from database and I would like details of one of the rows appear in a new table when I click on the "OPEN" button as in the screenshot below.
When I click on the OPEN button I get "No records found " as in the next screenshot below
Here is part of the index.xhtml
//
APP WEB
<p:ajax event="rowEdit" listener="#{transaction.onRowEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{transaction.onRowCancel}" update=":form1:messages" />
<p:column headerText="Reference">
<p:commandLink value="#{c.reference}" action="/faces/global/SingleTx.xhtml" target="_blank" >
<f:setPropertyActionListener target="#{transaction.showSelectedTx(reference)}" value="#{c}" />
</p:commandLink>
</p:column>
<p:column headerText="Rartner">
#{c.pname}
</p:column>
<p:column headerText="Status">
#{c.fk_status}
</p:column>
<p:column headerText="Sender">
#{c.sendername}
</p:column>
<p:column headerText="Beneficiary">
#{c.beneficiaryname}
</p:column>
<p:column headerText="Amounts">
#{c.beneficiary_currency} #{c.beneficiary_amount}
</p:column>
<p:column headerText="Action">
<p:commandButton style="float:right" value="Print" >
<p:confirm header="#{cd.reference}" message="Are you sure?" icon="ui-icon-alert" />
<p:button value="Open" href="/faces/global/SingleTx.xhtml" target="_self" />
</p:commandButton>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:dialog modal="true" width="800px" height="400px" widgetVar="singletx"
id="dialog">
Name :#{transaction.showSelectedTx(reference)}
</p:dialog>
</h:form>
Here is the backing bean:
package com.mycompany.data;
/**
*
* #author bryan
*/
import conn.DBConnector;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "transaction")
#SessionScoped
public class TransactionBean implements Serializable {
//added
private static final long serialVersionUID = 1L;
public String reference;
public String fk_status;
public String sendername;
public String beneficiaryname;
public String beneficiary_currency;
public double beneficiary_amount;
public String pname;
Transaction user;
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getFk_status() {
return fk_status;
}
public void setFk_status(String fk_status) {
this.fk_status = fk_status;
}
public String getSendername() {
return sendername;
}
public void setSendername(String sendername) {
this.sendername = sendername;
}
public String getBeneficiaryname() {
return beneficiaryname;
}
public void setBeneficiaryname(String beneficiaryname) {
this.beneficiaryname = beneficiaryname;
}
public String getBeneficiary_currency() {
return beneficiary_currency;
}
public void setBeneficiary_currency(String beneficiary_currency) {
this.beneficiary_currency = beneficiary_currency;
}
public double getBeneficiary_amount() {
return beneficiary_amount;
}
public void setBeneficiary_amount(double beneficiary_amount) {
this.beneficiary_amount = beneficiary_amount;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
//resource injection
#Resource(name = "jdbc/primefaces")
//connect to DB and get customer list
public List<Transaction> getTransactionList() throws SQLException, ClassNotFoundException {
Connection con = null;
con = DBConnector.getDBConnection();
if (con == null) {
throw new SQLException("Can't get database connection");
}
PreparedStatement ps
= con.prepareStatement(
"select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id");
//get customer data from database
ResultSet result = ps.executeQuery();
List<Transaction> list = new ArrayList<Transaction>();
while (result.next()) {
Transaction cust = new Transaction();
cust.setReference(result.getString("reference"));
cust.setFk_status(result.getString("name"));
cust.setSendername(result.getString("sendername"));
cust.setBeneficiaryname(result.getString("beneficiaryname"));
cust.setBeneficiary_currency(result.getString("beneficiary_currency"));
cust.setBeneficiary_amount(result.getDouble("beneficiary_amount"));
cust.setPname(result.getString("pname"));
//store all data into a List
list.add(cust);
}
return list;
//added
}
//view single transaction
private List<Transaction> selectSingleTx;
public Transaction getUser() {
return user;
}
public void setUser(Transaction user) {
this.user = user;
}
public List<Transaction> getSelectSingleTx() {
return selectSingleTx;
}
public void setSelectSingleTx(List<Transaction> selectSingleTx) {
this.selectSingleTx = selectSingleTx;
}
public void showSelectedTx(String reference){
Connection con=DBConnector.getDBConnection();
if(con==null){
System.out.println("No db connection");
}
String ref=getReference();
try {
String q="select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id where tx.reference="+ref+"";
PreparedStatement ps=null;
ResultSet rs=null;
ps.setString(1, reference);
rs=ps.executeQuery();
display(rs);
} catch (Exception e) {
}
}
public void selectTx(String reference){
showSelectedTx(reference);
}
// to be implemented later
private static void display(ResultSet myRs) throws SQLException {
while (myRs.next()) {
String sendername = myRs.getString("sendername");
String beneficiaryname = myRs.getString("beneficiaryname");
//double salary = myRs.getDouble("salary");
String department = myRs.getString("department");
System.out.printf("%s, %s \n", sendername, beneficiaryname);
}
}
}
//
As per the Reference link, you need to include the value of c.reference in the link
value="#{c.reference}"
See JSF ViewParam from CommandButton
or
How to pass a parameter along with h:commandButton

How to keep selected row after dialog closes Primefaces

In Primefaces 5.2, Glassfish 4.0, I am developping a simple CRUD. I have 2 distinct issues related to row selection.
The user clicks on a row in the datatable, this row is highlighted, the user selects "Edit" menu in the contextual menu, a modal window is opened.
1/ When the user press "Cancel" button in the modal window, the dialog is correctly closed. But then if the user selects another row in the datatable, the values displayed in the new modal window corresponds to the first previous selection. How to update the selected values?
2/ When the user press "OK" button in the modal window, the dialog is correctly closed, the datatable is correctly updated. But the updated row in the datatable is not anymore highlighted, the user doesn't know which row has just been updated. Is there a way to keep highlighted the lastly updated row (but to reinitialize the selected values for futher selection) until next click on a row, and in parallel of other focused row?
searchCompany.xhtml code is:
<h:form id="form">
<p:growl id="msgs" showDetail="true"/>
<p:contextMenu for="table">
<p:menuitem value="View" update="detail" icon="ui-icon-search" oncomplete="PF('companyDialog').show()"/>
<p:menuitem value="Delete" update="table" icon="ui-icon-close" actionListener="#{dtContextMenuView.deleteCompany}"/>
</p:contextMenu>
<p:dataTable
id="table"
value="#{companyBean.allCompanies}"
var="company"
editable="true"
editmode="row"
widgetVar="cellCompanies"
sortBy="#{company.name}"
scrollable="true"
scrollWidth="1024"
scrollHeight="300"
rowKey="#{company.id}"
selection="#{companyBean.selectedCompany}"
selectionMode="single">
<!-- above: by default table is sorted by Company name -->
<!-- above: to freeze the 2 first columns : frozenColumns="2"-->
<p:column
style="width:150px"
sortBy="#{company.name}"
filterBy="#{company.name}"
filterMatchMode="contains">
<!-- Column is sortable -->
<f:facet name="header">
#{msg['name']} <!-- Title of the column -->
</f:facet>
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{company.name}" />
</f:facet>
<f:facet name="input">
<h:inputText value="#{company.name}"/>
</f:facet>
</p:cellEditor>
</p:column>
(..)
</p:dataTable>
<p:dialog header="#{msg['detail']}" widgetVar="companyDialog" modal="true" showEffect="fade" resizable="false">
<p:panel id="detail" >
<p:panelGrid columns="2" rendered="#{not empty companyBean.selectedCompany}">
<h:outputText value="#{msg['name']}:" />
<p:inputText value="#{companyBean.selectedCompany.name}" />
<h:outputText value="#{msg['contact']}:" />
<p:inputText value="#{companyBean.selectedCompany.contact}" />
</p:panelGrid>
<p:commandButton action="#{companyBean.updateCompanyEnd}" value='#{msg.OK}' oncomplete="PF('companyDialog').hide();" update="table, :form:msgs"/>
<p:commandButton value='#{msg.cancel}' onclick="PF('companyDialog').hide();"/>
</p:panel>
</p:dialog>
</h:form>
</ui:define>
</ui:composition>
The bean code is :
package com.sdzee.bean;
#ManagedBean
#ViewScoped
public class CompanyBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final String CREATE_COMPANY = "createCompany";
private static final String DELETE_COMPANY = "deleteCompany";
private static final String UPDATE_COMPANY = "updateCompany";
private static final String LIST_ALL_COMPANIES = "searchCompany";
private static final String STAY_IN_THE_SAME_PAGE = null;
#EJB
private CompanyFacade companyFacade;
private Company company;
private List<Company> AllCompanies;
#PostConstruct
public void init() {
AllCompanies = companyFacade.findAll();
}
private Company selectedCompany;
public Company getCompany() {
if(company == null){
company = new Company();
}
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public List<Company> getAllCompanies() {
return AllCompanies;
}
public String updateCompanyEnd(){
try {
Company comp = selectedCompany;
companyFacade.update(comp);
} catch (EJBException e) {
FacesContext context = FacesContext.getCurrentInstance();
String texte = context.getApplication().evaluateExpressionGet(context, "#{msg['error']}", String.class);
sendErrorMessageToUser(texte+e);
return STAY_IN_THE_SAME_PAGE;
}
FacesContext context = FacesContext.getCurrentInstance();
String texte = context.getApplication().evaluateExpressionGet(context, "#{msg['update.successful']}", String.class);
FacesMessage message = new FacesMessage(texte, selectedCompany.getName());
FacesContext.getCurrentInstance().addMessage(null, message);
this.selectedCompany = company;
return LIST_ALL_COMPANIES;
}
public String deleteCompanyStart(){
return DELETE_COMPANY;
}
public String deleteCompanyEnd(){
try {
companyFacade.delete(company);
} catch (EJBException e) {
sendErrorMessageToUser("Error. Call the ADM");
return STAY_IN_THE_SAME_PAGE;
}
FacesContext context = FacesContext.getCurrentInstance();
String texte = context.getApplication().evaluateExpressionGet(context, "#{msg['delete.successful']}", String.class);
FacesMessage message = new FacesMessage(texte, company.getName());
FacesContext.getCurrentInstance().addMessage(null, message);
//sendInfoMessageToUser("Operation Complete: Delete");
return LIST_ALL_COMPANIES;
}
public String createCompanyStart(){
return CREATE_COMPANY;
}
public String createCompanyEnd(){
try {
companyFacade.save(company);
} catch (EJBException e) {
sendErrorMessageToUser("Error. Check if the weight is above 0 or call the adm");
return STAY_IN_THE_SAME_PAGE;
}
sendInfoMessageToUser("Operation Complete: Create");
return LIST_ALL_COMPANIES;
}
public String listAllCompanies(){
return LIST_ALL_COMPANIES;
}
private void sendInfoMessageToUser(String message){
FacesContext context = getContext();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
}
private void sendErrorMessageToUser(String message){
FacesContext context = getContext();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
}
private FacesContext getContext() {
FacesContext context = FacesContext.getCurrentInstance();
return context;
}
public Company getSelectedCompany() {
return selectedCompany;
}
public void setSelectedCompany(Company selectedCompany) {
this.selectedCompany = selectedCompany;
}
}