I'm new to xhtml and I am trying to use href inside a table's cell via a certain name(auction's name in my case). When I press the auction's name, I want to be send inside another page for adding a bid, seeing hightest bid and so on. It just shows me the last panel Group from the referenced page(where it says: No bids for this auction).
Can someone help me please ?
the code from rich:column is auctionList.xhtml:
<composite:implementation>
<rich:dataTable id="auctionsTable" rows="6" value="#{cc.attrs.auctions}" var="auct" border="1" styleClass="flat list auctions" rendered="#{cc.attrs.rendered and not empty cc.attrs.auctions}">
<f:facet name="header">
<rich:dataScroller forComponent="auctionsTable" />
</f:facet>
<h:link outcome="/destination" value="link" />
<rich:column sortBy="#{auct.name}" sortOrder="ascending" >
<a href="detail.xhtml">
#{auct.name}
</a>
</rich:column>
and detail.xhml is:
<ui:composition>
<h2>Details</h2>
<h:panelGroup layout="div"
rendered="#{auctionManager.currentAuction != null}">
<a4j:poll interval="3000" render="highestBidOutput, bidHistory" action="#{auctionManager.refreshAuction(currentAuction)}" />
<h3>#{currentAuction.name}</h3>
<h:panelGrid>
<h:column>
<h:outputLabel value="ID:" />
<h:outputText value="#{currentAuction.id}" />
</h:column>
<h:column>
<h:outputLabel value="Owner:" />
<h:outputText value="#{currentAuction.owner.name}" />
</h:column>
<h:column>
<h:outputLabel value="Original price:" />
<h:outputText value="#{currentAuction.originalPrice}" />
</h:column>
<h:column>
<h:outputLabel value="Description:" />
<h:outputText value="#{currentAuction.description}" />
</h:column>
<h:column>
<h:outputLabel value="Location:" />
<h:outputText value="#{currentAuction.location}" />
</h:column>
</h:panelGrid>
<h:panelGrid columns="2">
<h:outputLabel value="Highest bid:"
rendered="#{not empty currentAuction.highestBid}" />
<h:outputText id="highestBidOutput"
value="#{currentAuction.highestBid.amount} (#{currentAuction.highestBid.bidder.name})"
rendered="#{not empty currentAuction.highestBid}" />
<h:outputLabel value="Bid" rendered="#{loginManager.logged}" />
<h:form rendered="#{loginManager.logged}">
<h:inputText id="bidAmountInput" value="#{bidAmount}"
validator="#{bidValidator.validateBid}" />
<h:commandButton value="Add"
action="#{auctionManager.addBid(bidAmount)}" />
<h:messages style="color: red" />
</h:form>
</h:panelGrid>
<h:panelGroup id="bidHistory" rendered="#{not empty currentAuction.bids}">
<h3>Bids</h3>
<h:dataTable var="offer" value="#{currentAuction.bids}" border="1"
styleClass="flat">
<h:column>#{offer.bidder.name}</h:column>
<h:column>#{offer.amount}</h:column>
</h:dataTable>
</h:panelGroup>
</h:panelGroup>
<h:panelGroup layout="div"
rendered="#{auctionManager.currentAuction == null}">
<p>No bids for given auction.</p>
</h:panelGroup>
and AuctionManagerImpl.java used in detail.xhtml:
private static final long serialVersionUID = 1L;
private Auction currentAuction = null;
#PersistenceContext(type=PersistenceContextType.EXTENDED)
private EntityManager em;
#Inject
private LoginManager loginManagerBean;
#Resource SessionContext sessionContext;
#Produces
#Named
#Dependent
#CurrentAuction
#PermitAll
public Auction getCurrentAuction() {
if (currentAuction != null && !em.contains(currentAuction)) {
currentAuction = em.merge(currentAuction);
}
return currentAuction;
}
#PermitAll
public Long getCurrentAuctionId() {
return (currentAuction == null) ? null : currentAuction.getId();
}
#PermitAll
public void setCurrentAuctionId(Long currentId) {
this.currentAuction = em.find(Auction.class, currentId);
}
#PermitAll
public List<Auction> getAll() {
return em.createQuery("SELECT a FROM Auction a", Auction.class)
.getResultList();
}
#PermitAll
public List<Auction> getAuctionsWinningByUser(User user) {
String jql = "SELECT auction FROM Auction auction, User user "
+ "WHERE user=:user AND auction.highestBid member of user.bids "
+ "ORDER BY auction.id";
TypedQuery<Auction> query = em.createQuery(jql, Auction.class);
query.setParameter("user", user);
List<Auction> auctions = query.getResultList();
return auctions;
}
#PermitAll
public List<Auction> getAuctionLoosingByUser(User user) {
String jql = "SELECT DISTINCT auction FROM User user "
+ "JOIN user.bids bid JOIN bid.auction auction "
+ "WHERE user=:user AND auction.highestBid.bidder != user "
+ "ORDER BY auction.id";
TypedQuery<Auction> query = em.createQuery(jql, Auction.class);
query.setParameter("user", user);
List<Auction> auctions = query.getResultList();
return auctions;
}
#PermitAll
public void refreshAuction(Auction auction) {
em.refresh(auction);
}
//#PermitAll
public void addBid(long bidAmount) {
if (sessionContext.getCallerPrincipal() == null) {
throw new IllegalStateException(
"user must be logged in order to add bid");
}
if (currentAuction == null) {
throw new IllegalStateException(
"currentAuction have to be selected in order to add bid");
}
Bid bid = new Bid(loginManagerBean.getCurrentUser(), currentAuction, bidAmount);
em.persist(bid);
em.flush();
em.refresh(bid);
}
}
also very important is list.xhtml where I make use of auctionList.xhtml:
<ui:composition template="templates/home.xhtml">
<ui:param name="activeTab" value="list" />
<ui:define name="content">
<h2>Auction List</h2>
<a:auctionList auctions="#{auctionManager.all}" />
</ui:define>
Basicaly you need put a value in the request and redirect to destination page, using JSF, a method that have a String, implicitly return a navigation, you can make this in this way:
public String sendToPageAndPutValue(){
FacesContext.getCurrentInstance().getExternalContext().getFlash().put(paramName, paramValue);
return "pageDestination.xhtml";
}
To recover this value in destination Bean you can make this:
FacesContext.getCurrentInstance().getExternalContext().getFlash().get("paramName")
check in your bean.:
#Named -> javax.inject.Named
#ViewScoped -> org.omnifaces.cdi.ViewScoped
public class YourBean
In the your xhtml, you need call this method in a h:commandButton or a4j:commandButton using the property action
<h:commanButton id="idButton" value="Send" execute="#this" action="#{yourBean.sendToPageAndPutValue()}"/>
Related
I have an issue where I have a primefaces outputtext field and from the managed bean, I'm attempting to return an array type back to this field. Something is amiss in that I'm getting no return value back to my outputtext field. I will admit that I'm a bit rusty on my Java coding skills and it could be that I'm not performing something correctly within my bean method with respect to my return value.
My JSF page outputtext field
<p:panel id="horizontal" header="Conversion from Lat Long to MGRS" toggleable="true" toggleOrientation="horizontal">
<h:panelGrid columns="2" cellpadding="10" styleClass="left">
<h:outputLabel for="lat" value="Enter Latitude:" />
<p:inplace id="lat">
<p:inputText value="Latitude" />
</p:inplace>
<h:outputLabel for="long" value="Enter Longitude:" />
<p:inplace id="long">
<p:inputText value="Longitude" />
</p:inplace>
<h:outputLabel for="mgrs" value="MGRS conversion value:" />
<h:outputText id="mgrs" value="#{coordinates.MGRSCoordreturn}" />
<p:commandButton value="Submit" update="mgrs" icon="ui-icon-check" actionListener="#{coordinates.mgrsFromLatLon(lat, long)}"/>
</h:panelGrid>
</p:panel>
<h:outputLabel for="mgrs_input" value="Enter MGRS:" />
<p:inplace id="mgrs_input">
<p:inputText value="MGRS" />
</p:inplace>
<h:outputLabel for="mgrs_output" value="Lat Long conversion values:" />
<h:outputText id="mgrs_output" value="#{coordinates.latLongVReturn}" />
<p:commandButton value="Submit" update="mgrs_output" icon="ui-icon-check" actionListener="#{coordinates.latLonFromMgrs(mgrs_input)}"/>
My managed bean code:
#ManagedBean
#SessionScoped
public class Coordinates implements Serializable{
private String MGRSCoordreturn;
private Double LatLongVReturn;
public String mgrsFromLatLon(double lat, double lon){
// 37.10, -112.12
Angle latitude = Angle.fromDegrees(lat);
Angle longitude = Angle.fromDegrees(lon);
MGRSCoordreturn = MGRSCoord.fromLatLon(latitude, longitude).toString();
return MGRSCoord.fromLatLon(latitude, longitude).toString();
}
public String getMGRSCoordreturn() {
return MGRSCoordreturn;
}
public void setMGRSCoordreturn(String MGRSCoordreturn) {
this.MGRSCoordreturn = MGRSCoordreturn;
}
public double[] latLonFromMgrs(String mgrs){
MGRSCoord coord = MGRSCoord.fromString("31NAA 66021 00000");
double LatLongVReturn[] = new double[]{
coord.getLatitude().degrees,
coord.getLongitude().degrees
};
return new double[]{
coord.getLatitude().degrees,
coord.getLongitude().degrees
};
}
public Double getLatLongVReturn() {
return LatLongVReturn;
}
public void setLatLongVReturn(Double LatLongVReturn) {
this.LatLongVReturn= LatLongVReturn;
}
}
Sidenote: It works with Command-Buttons.
What I Have:
A simple form where name and address from a customer are entered. In a data-table below, each row contained (in the working version) the following fields:
Name of the customer
A Command-Button which redirects to another page and shows the customers orders (This worked using <p: commandButton immediate="true">)
Another Command-Button which displayed the past orders.
Another Command-Button which was responsible for updating customer-data.
Since I didn't want to have three Command-Buttons in each row I decided to use a Split-Button.
Problem:
<p:splitButton immediate="true">
The form asks me to fill the missing data (name and address) which are set to required="true.
Question:
As far as I understand the attribute immediate="true is used to overcome this issue. So what am I missing ?
Code:
<h:form>
<p:growl id="growl" sticky="false" life="3500" showDetail="false"/>
<h:panelGrid id="customer_grid" columns="2" cellspacing="1" cellpadding="5">
<h:outputLabel id="label" for="name" value="Kunde:" style="font-weight:bold"/>
<p:inputText id="name" value="#{customerController.customer.name}" required="true" requiredMessage="Name eingeben!"/>
<h:outputLabel for="address" value="Adresse:" style="font-weight: bold" />
<p:inputText id="address" value ="#{customerController.customer.address}" required="true" requiredMessage="Adresse eingeben!"/>
<p:commandButton action = "#{customerController.createCustomer}" value="Speichern" style="margin-right:10px"
actionListener="#{growlController.saveMessage}" ajax="true"
onclick="PF('blockUIWidget').block()" oncomplete="PF('blockUIWidget').unblock()" styleClass="save-button"/>
<p:commandButton onclick="history.back(); return false;" value="Abbrechen" ajax="true"/>
<pe:blockUI widgetVar="blockUIWidget">
<h:panelGrid columns="2">
<p:graphicImage id="loader" name="images/ajax-loader.gif" style="margin-right: 12px; vertical-align: middle;" rendered="true"/>
<h:outputText value="Please wait..." style="white-space: nowrap;"/>
</h:panelGrid>
</pe:blockUI>
</h:panelGrid>
<br/>
<br/>
<p:dataTable var="customer" value="#{customerController.allCustomers}" resizableColumns="true" tableStyle="width: auto"
rendered="#{not empty customerController.allCustomers}">
<p:column headerText="customer" style="width: 300px">
<h:outputText value="#{customer.name}" />
</p:column>
<p:column>
<p:splitButton value="current order" action="#{userController.setup(customer, 'lastOrder')}" immediate="true">
<p:menuitem value="old orders" action="#{userController.setup(customer, 'oldOrders')}" immediate="true"/>
<p:menuitem value="edit" action="#{userController.setup(customer, 'update')}" immediate="true"/>
</p:splitButton>
</p:column>
</p:dataTable>
EDIT:
According to the comment of BalusC I've put the two parts in separate forms.
Effect: The message to fill out the above form does not show up, but the redirect is not happening either.
EDIT2:
The purpose of the method userController.setup(customer, 'String') is basically to inject the customer who is represented for each row. The String is returned for redirecting purposes which are set in the faces-config.xml and as I said: It works when I use Command-Buttons instead.
CODE:
#Named
#SessionScoped
public class UserController implements Serializable{
#Inject
private Customer customer;
#EJB
private CustomerService customerService;
public UserController(){
}
public List<Item> getItems(){
return customerService.getItems(customer);
}
public Ordery getCurrentOrder(){
return customerService.getCurrentOrder(customer);
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public String setup(Customer customer, String nav){
this.customer = customer;
return nav;
}
public void update(){
customerService.update(customer);
}
}
i am using jsf and i am trying to show a hidden panel this what i tried
<h:commandButton update=":outPanel" actionListener="#{SelectBean.mod1()}" image="Ressources/images/update.png" style="vertical-align:middle" >
Modifier
</h:commandButton>
<p:panel visible="#{SelectBean.bol}" closable="true" toggleable="true" id="outPanel" styleClass="outPanel" widgetVar="outpanel">
<h:outputLabel value="Nom " />
<h:inputText value="#{SelectBean.nom}" />
<br/>
<h:outputLabel value="Experience " />
<h:inputText value="#{SelectBean.exp}" />
<br/>
<h:commandButton value="Modifier"/>
</p:panel>
my bean is
private boolean bol=false;
public boolean getBol() {
return bol;
}
public void setBol(boolean bol) {
this.bol = bol;
}
public String mod1()
{
bol = true;
return "success";
}
but this thing not working the panel is always hidden.
Try like this, your panel will be shown if bol is true
<p:panel rendered="#{selectBean.bol}" closable="true" toggleable="true" id="outPanel" styleClass="outPanel" widgetVar="outpanel">
Also i think you have wrong syntax, you should call methods and variables of your class through selectBean but not SelectBean
I have a jsf page that I can't update the value of some checkboxes in a list of userDamain objects, in fact this is a part of my jsf page :
<h:outputText value="USER's rights list: "></h:outputText>
<p:dataTable id="userss" var="userr" value="#{userMB.userListe}">
<p:column>
<f:facet name="header"><h:outputText value="FirstName" /></f:facet>
<h:outputText value="#{userr.firstName}" />
</p:column>
<p:column>
<h:panelGrid columns="1" style="margin-bottom:10px" cellpadding="5">
<h:outputText value="Basic Usage: " />
<p:selectBooleanCheckbox value="#{userr.deletee}" immediate="true" actionListener="#{userr.deletee}" />
</h:panelGrid>
<p:commandButton value="Submit" update="display" oncomplete="dlg.show()" />
<p:dialog header="Selected Values" modal="true" showEffect="fade" hideEffect="fade" widgetVar="dlg">
<h:panelGrid columns="1" id="display">
<h:outputText value="Value 1: #{userr.deletee}" />
</h:panelGrid>
</p:dialog>
</p:column>
when I click on the boolean button 'Submit', the value of the userr.deletee is always false ( the default value ) and it's not updated anyway, I tried to use the Listner and actionListener in the booleanButton but it doesn't work, I also tried the postValidate event, so if someone has any idea of that, I would be graceful.
this is a part of my managed bean:
private List<UserDomain> userListe ;
public List<UserDomain> getUserListe() {
return this.userListe;
}
public void loadUserListe(){
this.userListe = new ArrayList<UserDomain>();
this.userListe.addAll(getUserServicee().getAll());
}
public void setUserListe(List<UserDomain> userListe) {
this.userListe = userListe;
}
a part of the userDomain bean:
...
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Transient
private boolean deletee;
public boolean isDeletee() {
return deletee;
}
public void setDeletee(boolean deletee) {
this.deletee = deletee;
}
I found out a solution which seems logic to me, I added to my checkbox an ajax behavior to execute a method and an attribute which called in this method to get the whole userDomain object, so on I can get the user.deletee value, here is a part of the code I m talking about:
<h:panelGrid columns="1" style="margin-bottom:10px" cellpadding="5">
<h:outputText value="Delete Right: " />
<p:selectBooleanCheckbox value="#{userr.deletee}">
<f:ajax execute="#this" listener="#{userMB.saveUserRights}" />
<f:attribute name="user" value="#{userr}" />
</p:selectBooleanCheckbox>
</h:panelGrid>
I hope this will be helpful for you
I have a form with some inputs which has a ViewScoped *ManagedBean* behind. At the bottom of the form I have a CommandButton for saving the data. There is a datatable on the form which new items could be added by entering data to an input and clicking another CommandButton. When user filled all the inputs and added any items to the datatable he/she can click the save button. But I have some problems in controling the add button and updating the datamodel. When I set the immadiate of the button to true the value of the input won't update and when I set it to false validation error will happen for the rest of the inputs on the form!!!
Code if it helps:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
template="./templates/master.xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns="http://www.w3.org/1999/xhtml">
<ui:define name="windowTitle">
#{lbls.registerWaggon}
</ui:define>
<ui:define name="sectionTitle">
<h:panelGroup layout="block" styleClass="sectionTitle">
<h:graphicImage library="img" name="railways.png"/>
</h:panelGroup>
</ui:define>
<ui:define name="right">
<ui:include src="templates/railwaysright.xhtml"/>
</ui:define>
<ui:define name="extraCSS">
<h:outputStylesheet library="css" name="persiancalendar.css"/>
<h:outputStylesheet library="css" name="grid.css"/>
</ui:define>
<ui:define name="extraJS">
<h:outputScript library="js" name="lib/persiancalendar.js"/>
</ui:define>
<ui:define name="content">
<h:panelGroup rendered="#{!current.hasLoggedIn()}">
<h:panelGroup layout="block" styleClass="warningBox">
<h:outputText value="#{app.youHaveNotLoggedIn}"/>
<br/>
<h:link value="#{lbls.login}" outcome="login"/>
</h:panelGroup>
</h:panelGroup>
<p:panel rendered="#{current.hasLoggedIn() and requestWaggon.isViewable()}">
<f:facet name="header">
<h:outputText value="#{lbls.registerWaggonLong}" />
</f:facet>
<h:form id="frmRequest">
<h:panelGrid columns="3" footerClass="buttons">
<h:outputText value="#{lbls.number}:"/>
<h:inputText id="number" label="#{lbls.number}" styleClass="ltr" value="#{requestWaggon.request.number}" readonly="true" />
<h:message for="number" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.requestDate}:"/>
<h:inputText styleClass="ltr" id="date" label="#{lbls.requestDate}" value="#{requestWaggon.request.date}" required="true" readonly="true">
<f:converter converterId="ir.khorasancustoms.DateConverter"/>
</h:inputText>
<h:message for="date" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.nameOfMaterialOwner}:"/>
<h:inputText id="ownerName" label="#{lbls.nameOfMaterialOwner}" value="#{requestWaggon.request.fullName}" required="true" readonly="true"/>
<h:message for="ownerName" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.companyName}:"/>
<h:inputText id="companyName" label="#{lbls.companyName}" value="#{requestWaggon.request.companyName}" required="true" readonly="true"/>
<h:message for="companyName" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.nameOfMaterial}:"/>
<h:inputText id="nameOfMaterial" label="#{lbls.nameOfMaterial}" value="#{requestWaggon.request.materialName}" required="true" readonly="true"/>
<h:message for="nameOfMaterial" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.materialWeight}:"/>
<h:panelGroup>
<h:inputText id="materialWeight" styleClass="ltr" label="#{lbls.materialWeight}" value="#{requestWaggon.request.materialWeight}" required="true" style="min-width: 0px; width: 60px" readonly="true"/>
<h:outputText value=" #{requestWaggon.request.weightUnit}"/>
</h:panelGroup>
<h:message for="materialWeight" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.senderAddress}:"/>
<h:inputText id="senderAddress" label="#{lbls.senderAddress}" value="#{requestWaggon.request.address}" required="true" style="width: 350px;" readonly="true"/>
<h:message for="senderAddress" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.receiverAddress} (#{lbls.country}):"/>
<h:outputText value="#{requestWaggon.request.country}"/>
<h:message for="country" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.station}:"/>
<h:inputText id="station" label="#{lbls.station}" value="#{requestWaggon.request.station}" required="true" readonly="true"/>
<h:message for="station" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.loadingDate}:"/>
<h:panelGroup>
<h:inputText styleClass="ltr" id="loadingDate" label="#{lbls.loadingDate}" value="#{requestWaggon.request.loadingDate}" required="true" readonly="true">
<f:converter converterId="ir.khorasancustoms.DateConverter"/>
</h:inputText>
</h:panelGroup>
<h:message for="loadingDate" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.boundryStation}:"/>
<h:outputText value="#{requestWaggon.request.bountryStation}"/>
<h:message for="boundryStation" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value=""/>
<h:outputText value=""/>
<h:outputText value=""/>
<h:outputText value="#{lbls.confirmDate}:"/>
<h:panelGroup>
<h:inputText styleClass="date ltr" id="confirmDate" label="#{lbls.confirmDate}" value="#{requestWaggon.request.confirmDate}" required="true">
<f:converter converterId="ir.khorasancustoms.DateConverter"/>
</h:inputText>
<input type="button" value="..." onclick="displayDatePicker('frmRequest:confirmDate', this);" class="datePicker"/>
</h:panelGroup>
<h:message for="confirmDate" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.confirm}:" styleClass="b"/>
<h:selectOneMenu value="#{requestWaggon.request.confirm}">
<f:selectItem/>
<f:selectItems value="#{searchRequest.allConfirms}" var="confirm" itemLabel="#{searchRequest.confirmCaption(confirm)}" itemValue="#{confirm}"/>
</h:selectOneMenu>
<h:message for="confirm" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.description}:"/>
<h:inputText id="description" label="#{lbls.description}" value="#{requestWaggon.request.confirmDescription}" required="false" style="width: 350px;"/>
<h:message for="description" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
<h:outputText value="#{lbls.waggonType}:"/>
<h:selectOneMenu id="waggonType" label="#{lbls.waggonType}" value="#{requestWaggon.request.waggonType}" required="true">
<f:selectItem/>
<f:selectItems value="#{requestWaggon.waggonTypes}"/>
<f:converter converterId="ir.khorasancustoms.CatalogValueFixedConverter"/>
</h:selectOneMenu>
<h:message for="waggonType" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>
**<h:outputText value="#{lbls.specialWaggonNumber}:"/>
<h:panelGroup>
<h:inputText id="specialWaggonNumber" label="#{lbls.specialWaggonNumber}" binding="#{requestWaggon.waggonNumberComponent}" />
<h:commandButton value="#{lbls.add}" action="#{requestWaggon.addWaggon}" immediate="true"/>
</h:panelGroup>
<h:message for="specialWaggonNumber" infoClass="info" warnClass="warning" errorClass="error" fatalClass="fatal"/>**
<h:outputText value="#{lbls.waggons}:"/>
<h:dataTable value="#{requestWaggon.waggonsDataModel}" var="waggon" columnClasses="index,,action" styleClass="grid" headerClass="title" rowClasses="two,three,one">
<h:column>
<f:facet name="header">#{lbls.index}</f:facet>
<h:outputText value="#{searchRequest.datamodel.rowIndex + 1}"/>
</h:column>
<h:column>
<f:facet name="header">#{lbls.number}</f:facet>
<h:outputText value="#{waggon.number}"/>
</h:column>
<h:column>
<f:facet name="header">#{lbls.action}</f:facet>
<h:commandLink action="delete">
<h:graphicImage styleClass="nb" alt="#{lbls.delete}" title="#{lbls.delete}" library="img" name="delete.png"/>
<f:param name="id" value="#{waggon.id}"/>
</h:commandLink>
</h:column>
</h:dataTable>
<f:facet name="footer">
<h:button outcome="searchrequest" value="#{lbls.cancel}" rendered="#{requestWaggon.id ne null}"/>
<h:commandButton action="#{requestWaggon.doNew}" value="#{lbls.new}" rendered="#{requestWaggon.request.id ne null}"/>
<h:commandButton action="#{requestWaggon.save}" value="#{lbls.ok}"/>
</f:facet>
</h:panelGrid>
<h:outputScript>
focusElement('frmRequest:confirmDate');
</h:outputScript>
</h:form>
<f:facet name="footer">
<h:messages styleClass="boxMessages" layout="table" infoClass="infoBox" warnClass="warningBox" errorClass="errorBox" fatalClass="errorBox" globalOnly="true"/>
<h:link outcome="searchrequest" value="#{lbls.searchRequestWaggon}"/>
</f:facet>
</p:panel>
<p:panel rendered="#{current.hasLoggedIn() and !requestWaggon.isViewable()}">
<h:panelGroup layout="block" styleClass="warningBox">
<h:outputText value="#{app.accessDenied}" />
</h:panelGroup>
</p:panel>
</ui:define>
</ui:composition>
bean
#ManagedBean(name = "requestWaggon")
#ViewScoped
public class RequestWaggonBean {
//<editor-fold defaultstate="collapsed" desc="FIELDS">
private Logger logger;
#ManagedProperty(value = "#{current}")
private CurrentSessionBean current;
private RequestWaggon request;
private Set<CatalogValue> weightUnits;
private Set<CatalogValue> countries;
private Set<CatalogValue> boundryStations;
private Set<CatalogValue> waggonTypes;
private Integer id;
#ManagedProperty(value = "#{searchRequest}")
private SearchRequestBean searchRequest;
private Integer newWaggonNumber;
private HtmlInputText waggonNumberComponent;
private DataModel<Waggon> waggonsDataModel;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="CONSTRUCTORS">
public RequestWaggonBean() {
logger = LogUtil.getLogger(RequestWaggonBean.class);
request = new RequestWaggon();
ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest httpRequest = (HttpServletRequest) exContext.getRequest();
String strId = httpRequest.getParameter("id");
try {
id = Integer.parseInt(strId);
} catch (Exception ex) {
logger.fatal(ex);
}
}
#PostConstruct
public void init() {
request.setDate(current.getDate());
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
ResourceBundle app = ResourceBundle.getBundle("application");
try {
//session.beginTransaction();
if (id != null) {
request = (RequestWaggon) session.get(RequestWaggon.class, id);
}
Query query = session.createQuery("from CatalogGroup as catalogGroup where catalogGroup.englishTitle = :englishTitle");
query.setParameter("englishTitle", "WeightUnit");
CatalogGroup weightUnit = (CatalogGroup) query.uniqueResult();
weightUnits = weightUnit.getValues();
query.setParameter("englishTitle", "Country");
CatalogGroup country = (CatalogGroup) query.uniqueResult();
countries = country.getValues();
query.setParameter("englishTitle", "BoundryStation");
CatalogGroup boundryStation = (CatalogGroup) query.uniqueResult();
boundryStations = boundryStation.getValues();
query.setParameter("englishTitle", "WaggonType");
CatalogGroup waggonType = (CatalogGroup) query.uniqueResult();
waggonTypes = waggonType.getValues();
//session.getTransaction().commit();
} catch (Exception ex) {
logger.fatal(ex);
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
} finally {
session.close();
}
Waggon[] arrayWaggons = new Waggon[request.getWaggons().size()];
arrayWaggons = request.getWaggons().toArray(arrayWaggons);
waggonsDataModel = new ArrayDataModel<Waggon>(arrayWaggons);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="METHODS">
public void save() {
boolean canSave = false;
String cantSaveMessage = "";
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
ResourceBundle app = ResourceBundle.getBundle("application");
try {
session.beginTransaction();
int number = 0;
if (request.getNumber() == null) {
number = RequestWaggon.nextNumber();
}
if (request.getNumber() != null || number > 0) {
if (request.getNumber() == null) {
request.setNumber(number);
canSave = isInsertable();
cantSaveMessage = app.getString("insertDenied");
} else {
canSave = isEditable();
cantSaveMessage = app.getString("editDenied");
}
if (canSave) {
session.saveOrUpdate(request);
RequestWaggonHistory history = new RequestWaggonHistory(request, current.getUser(), number > 0 ? 'I' : 'U', current.getIP());
session.save(history);
session.getTransaction().commit();
String message = app.getString("savedSuccessfully");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, cantSaveMessage, cantSaveMessage));
}
} else {
logger.fatal("Getting next number failed!");
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
}
} catch (Exception ex) {
logger.fatal(ex);
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
} finally {
session.close();
}
}
public void addWaggon(ValueChangeEvent event) {
ResourceBundle app = ResourceBundle.getBundle("application");
String strNewWaggonNumber = event.getNewValue().toString();
Integer newWaggonNumber = Integer.parseInt(strNewWaggonNumber);
if (newWaggonNumber == null || newWaggonNumber <= 0) {
String message = app.getString("EnterWaggonNumber");
FacesContext.getCurrentInstance().addMessage("frmRequest:specialWaggonNumber", new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
} else {
Waggon newWaggon = new Waggon();
newWaggon.setNumber(newWaggonNumber);
request.getWaggons().add(newWaggon);
Waggon[] arrayWaggons = new Waggon[request.getWaggons().size()];
arrayWaggons = request.getWaggons().toArray(arrayWaggons);
waggonsDataModel = new ArrayDataModel<Waggon>(arrayWaggons);
}
}
public boolean isViewable() {
return current.isViewable();
}
public boolean isDeletable() {
return current.isDeletable() && request.getWaggons().isEmpty();
}
public boolean isInsertable() {
return current.isInsertable();
}
public boolean isEditable() {
return current.isEditable() && request.getConfirm() == null;
}
public void doNew() {
request = new RequestWaggon();
request.setDate(current.getDate());
}
public String delete() {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
ResourceBundle app = ResourceBundle.getBundle("application");
try {
session.beginTransaction();
session.delete(request);
RequestWaggonHistory history = new RequestWaggonHistory(request, current.getUser(), 'D', current.getIP());
session.save(history);
session.getTransaction().commit();
searchRequest.search();
String message = app.getString("deletedSuccessfully");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
} catch (ConstraintViolationException ex) {
String message = app.getString("constraintViolation");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, message, message));
} catch (Exception ex) {
logger.fatal(ex);
Transaction tx = session.getTransaction();
if (tx.isActive()) {
tx.rollback();
}
String message = app.getString("databaseConnectionFailed");
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message));
} finally {
session.close();
}
return "searchrequest";
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="PROPERTIES">
public RequestWaggon getRequest() {
return request;
}
public void setRequest(RequestWaggon requestWaggon) {
this.request = requestWaggon;
}
public CurrentSessionBean getCurrent() {
return current;
}
public void setCurrent(CurrentSessionBean current) {
this.current = current;
}
public Set<CatalogValue> getWeightUnits() {
return weightUnits;
}
public void setWeightUnits(Set<CatalogValue> weightUnits) {
this.weightUnits = weightUnits;
}
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public Set<CatalogValue> getCountries() {
return countries;
}
public void setCountries(Set<CatalogValue> countries) {
this.countries = countries;
}
public Set<CatalogValue> getBoundryStations() {
return boundryStations;
}
public void setBoundryStations(Set<CatalogValue> boundryStations) {
this.boundryStations = boundryStations;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public SearchRequestBean getSearchRequest() {
return searchRequest;
}
public void setSearchRequest(SearchRequestBean searchRequest) {
this.searchRequest = searchRequest;
}
public Set<CatalogValue> getWaggonTypes() {
return waggonTypes;
}
public void setWaggonTypes(Set<CatalogValue> waggonTypes) {
this.waggonTypes = waggonTypes;
}
public Integer getNewWaggonNumber() {
return newWaggonNumber;
}
public void setNewWaggonNumber(Integer newWaggonNumber) {
this.newWaggonNumber = newWaggonNumber;
}
public DataModel<Waggon> getWaggonsDataModel() {
return waggonsDataModel;
}
public void setWaggonsDataModel(DataModel<Waggon> waggonsDataModel) {
this.waggonsDataModel = waggonsDataModel;
}
public HtmlInputText getWaggonNumberComponent() {
return waggonNumberComponent;
}
public void setWaggonNumberComponent(HtmlInputText waggonNumberComponent) {
this.waggonNumberComponent = waggonNumberComponent;
}
//</editor-fold>
}
The h:commandButton submits the whole form and all elements will be validated. You can use ajax to do a partial submit. Try the following:
Give your datatable an id value. So you can reference it from your commandButton:
<h:panelGroup id="tableWrapper">
<h:datatable id="mytable" value="#{requestWaggon.waggonsDataModel}" ..>
...
</h:datatable>
</h:panelGroup>
Then put an <f:ajax> inside your commandButton. The render and execute attributes must contain the id of your datatable; immediate=true is not needed:
<h:commandButton value="#{lbls.add}" action="#{requestWaggon.addWaggon}">
<f:ajax render="tableWrapper" execute="mytable"/>
</h:commandButton>