Send p:autoComplete value as a param in JSF - jsf

i have a rare situation in my page i have a "p:autoComplete" which is bind to a backing bean i can read that auto complete item form the backing bean.
but the problem is the selected value from that auto complete need to be passed as a parameter, when user pressed the button, with some other parameters. which i really don't know how to do it?
this is my page which has the autocomplete
<p:panel header="Employee sales" style="width:500px"
toggleable="true" toggleSpeed="500" closeSpeed="500">
<p:autoComplete id="user_auto_complete"
value="#{salesReportMainController.userFromAutoComplete}"
completeMethod="#{salesReportMainController.completeUser}"
var="user" itemLabel="#{user.userName}" itemValue="#{user}"
converter="#{userConverter}" forceSelection="true" />
<p:commandButton id="Search" value="Generate"
action="admin_common_barchart">
<f:param name="todaysDate"
value="#{salesReportMainController.todaysDate}" />
<f:param name="beforDate"
value="#{salesReportMainController.dateBeforOneYear}" />
<f:param name="employeeName"
value="#{salesReportMainController.userFromAutoComplete.userName}" />
</p:commandButton>
</p:panel>
and this is the backing bean that binds to that page
#ViewScoped
public class SalesReportMainController implements Serializable{
private static final long serialVersionUID = 1L;
#ManagedProperty(value = "#{userService}")
public UserService userService;
public DateTime todaysDate;
public DateTime dateBeforOneYear;
public DateTime dateBeforsixMonths;
public List<User> allUsers;
public List<User> acFilterdUsers;
public User userFromAutoComplete;
#PostConstruct
public void init(){
int oneYear = ConstantConfiguration.YearsInMonths.ONE_YEAR.getValue();
int sixMonths = ConstantConfiguration.YearsInMonths.SIX_MONTH.getValue();
todaysDate = new DateTime();
dateBeforOneYear = new DateTime(todaysDate).minusMonths(oneYear);
dateBeforsixMonths = new DateTime(todaysDate).minusMonths(sixMonths);
}
// public String buttonClick(){
// System.out.println("aaaaaaaa");
// return null;
// }
public List<User> completeUser(String query) {
allUsers = userService.getAllUsers();
acFilterdUsers = new ArrayList<User>();
for (User user : allUsers) {
if(user.getUserName().toLowerCase().startsWith(query)){
acFilterdUsers.add(user);
}
}
return acFilterdUsers;
}
public String getAutoCompleteUser() {
if (userFromAutoComplete != null) {
//i can get the value of the selected item form auto complete
}
return null;
}
//getters and setters
}
and this is the page that i want to load
<h:form id="common_chart_form" prependId="flase">
<p:growl id="growl" showDetail="true" autoUpdate="true"
sticky="false" />
<p:outputLabel id="labelvalue" value="aaaaaaaaaa"/>
<p:chart id="chart" type="bar"
model="#{commonChartController.barModel}" style="height:600px" />
<p:commandButton value="Print" type="button" icon="ui-icon-print">
<p:printer target="chart" />
</p:commandButton>
<p:commandButton value="Back" action="admin_sales_reports" />
</h:form>
and this the backing bean of the above page
#Component
#ManagedBean
#RequestScoped
public class CommonChartController implements Serializable{
private static final long serialVersionUID = 1L;
#ManagedProperty(value = "#{orderService}")
public OrderService orderService;
#ManagedProperty(value = "#{userService}")
public UserService userService;
List<MonthSales> salesList;
private BarChartModel barModel;
#PostConstruct
public void init() {
String dateTo = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("todaysDate");
String dateFrom = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("beforDate");
String employeeName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("employeeName");
System.out.println("user Name : "+employeeName);
if(employeeName != null && !employeeName.equals("")){
User user = userService.getUserByUserName("admin");
salesList = orderService.getMonthlySalesByUserName(UserUtility.stringDateToJodaDateTime(dateFrom).toDate(), UserUtility.stringDateToJodaDateTime(dateTo).toDate(), user);
createBarModel(salesList, user);
}else {
salesList = orderService.getMonthlySales(UserUtility.stringDateToJodaDateTime(dateFrom).toDate(), UserUtility.stringDateToJodaDateTime(dateTo).toDate());
createBarModel(salesList);
}
//
// salesList = orderService.getMonthlySales(UserUtility.stringDateToJodaDateTime(dateFrom).toDate(), UserUtility.stringDateToJodaDateTime(dateTo).toDate());
// createBarModel(salesList);
}
}
i can read the "dateTo" param and "dateFrom" param. problem is "employeeName" param is alwayas null

Related

How to create dynamic checkboxes using a list of objects in JSF?

I have an object with this attributes: Id, name and status, and I have a List of this object. I want to save the status (enable or disable) for each element.
You can use SelectManyCheckbox Primefaces Component.
<p:selectManyCheckbox id="checkboxTest" value="#{myBean.selectedElements}">
<f:selectItems value="#{myBean.myElements}" var="elem" itemLabel="#{elem.value}" itemValue="#{elem.id}" />
</p:selectManyCheckbox>
You need to create in your backing bean a list that will be filled by the selected element (selectedElements in the example above) and use your list of object (myElements) to create the checkbox on the page. In this way on submit you will have the "selectedElements" list filled with the checked items.
See more:
Primefaces ManyCheckbox
here is a general example (using <h:dataTable...>):
XHTML:
<h:form>
<h:dataTable var="row" value="#{categoryMan.items}">
<h:column>
<h:selectBooleanCheckbox value="#{row.enabled}">
</h:selectBooleanCheckbox>
</h:column>
<h:column>
<h:outputText value="#{row.id}"></h:outputText>
</h:column>
<h:column>
<h:outputText value="#{row.name}"></h:outputText>
<f:facet name="footer">
<h:commandButton action="#{categoryMan.save}" value="Save">
</h:commandButton>
</f:facet>
</h:column>
</h:dataTable>
</h:form>
YourBean:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="categoryMan")
#SessionScoped
public class CategoryManager implements Serializable {
private static final long serialVersionUID = -8453216983786165042L;
private List<Category> items;
public CategoryManager() {
}
#PostConstruct
private void init(){
try{
this.items = new ArrayList<Category>();
this.items.add(new Category("PS2001", "JSF", false));
this.items.add(new Category("PS2002", "ASP", true));
this.items.add(new Category("PS2002", "PHP", false));
}catch(Exception e){
e.printStackTrace();
}
}
public String save() {
for(Category cat: this.items){
System.out.println(cat.getName()+": "+cat.isEnabled());
}
return "yourNavigationRule";
}
public List<Category> getItems() {
return items;
}
public void setItems(List<Category> items) {
this.items = items;
}
}
Your Object:
import java.io.Serializable;
public class Category implements Serializable{
private static final long serialVersionUID = -8070175380194294502L;
private String id;
private String name;
private boolean enabled;
public Category(String id, String name, boolean enabled) {
super();
this.id = id;
this.name = name;
this.enabled = enabled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
This is how i have displayed the list of dynamic checkboxes with specific question.
<p:row styleClass="ui-panelgrid-cell" rowspan="3">
<p:column>
<div style="overflow: auto; width: 100%;">
<p:dataTable var="tQuestions"
value="#{userPreferences.availableQuestions}"
emptyMessage="No Questions Found." id="sTable">
<p:column>
<h:outputText id="sName" styleClass="cellLabelMand"
value="#{tQuestions.shortText}" />
<h:outputText value="<br/><br/>" escape="false" />
<ui:repeat var="tCategoryList" value="#{tQuestions.categoryList}">
<p:selectBooleanCheckbox value="checked" />
<h:outputText value="#{tCategoryList.categoryValue}" />
</ui:repeat>
</p:column>
</p:dataTable>
</div>
</p:column>
</p:row>

Removing row datatable?

I have an entity that contain an attribute with #ElementCollection annotation. This attribute is a list of String that I add telphones(telefones). I display this telphones at a dataTable of primefaces.
How I can remove this telphone with row selected ?
I'm trying this.
Entity
#Entity
public class UnidadeEscolar implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#NotNull #Size(min=5, message="Informe o nome da unidade escolar")
#Column(unique=true)
private String nome;
private String departamento;
#Embedded
private Endereco endereco;
#ElementCollection
#JoinTable(name="telefones_ue", joinColumns=#JoinColumn(name="ue_id"))
private List<String> telefones = new ArrayList<String>();
/** adiciona telefones */
public void addTelefone(String tel){
telefones.add(tel);
}
/** remove telefone */
public void removeTelefone(int row){
telefones.remove(row);
}
Managed Bean
#ManagedBean
#ViewScoped
public class UnidadeEscolarMB implements Serializable{
private static final long serialVersionUID = 1L;
private UnidadeEscolar bean;
private GenericDAO<UnidadeEscolar> dao;
private List<UnidadeEscolar> unidades = null;
private String telefone = "";
/** add telphone to entity */
public void addTelefones(){
//System.out.println(telefone);
bean.addTelefone(telefone);
telefone = "";
}
/** remove telphone of entity */
public void removeTelefone(){
bean.getTelefones().remove(telefone);
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
xhtml
<p:tab title="Contato">
<p:fieldset legend="Telefones">
<p:dataTable id="tabelaTelefones" widgetVar="datalistTelefones"
value="#{unidadeEscolarMB.bean.telefones}" var="fone"
emptyMessage="Nenhum registro encontrado"
selectionMode="single"
selection="#{unidadeEscolarMB.telefone}"
rowKey="#{unidadeEscolarMB.bean.id}"
>
<p:column headerText="Telefone">
<h:outputText value="#{fone}"/>
</p:column>
</p:dataTable>
<p:commandButton actionListener="#{unidadeEscolarMB.removeTelefone()}" value="-" update="tabelaTelefones"/>
</p:tab>
How I can delete telphone selected at dataTable ?
I solved the problem using <f:setPropertyActionListener/>
here how I did
<p:tab title="Contato">
<p:fieldset legend="Telefones">
<p:dataTable id="tabelaTelefones" widgetVar="datalistTelefones"
value="#{unidadeEscolarMB.bean.telefones}" var="fone"
emptyMessage="Nenhum registro encontrado"
>
<p:column headerText="Telefone">
<h:outputText value="#{fone}"/>
</p:column>
<p:column headerText="">
<p:commandLink action="#{unidadeEscolarMB.removeTelefone()}" value="Excluir" update="tabelaTelefones">
<f:setPropertyActionListener target="#{unidadeEscolarMB.telefone}" value="#{fone}"/>
</p:commandLink>
</p:column>
</p:dataTable>
<p:inputMask id="telefone" widgetVar="telefoneMask" value="#{unidadeEscolarMB.telefone}" mask="(99)9-9999-9999" />
<p:commandButton actionListener="#{unidadeEscolarMB.addTelefones()}" value="+" update="telefone, tabelaTelefones"/>
<p:selectBooleanCheckbox itemLabel="Adiciona9" onchange="setMaskTelefone()" id="checkBox" widgetVar="ckbox9" value="true" immediate="true"/>
</p:fieldset>
</p:tab>
#ManagedBean
#ViewScoped
public class UnidadeEscolarMB implements Serializable{
private static final long serialVersionUID = 1L;
private UnidadeEscolar bean;
private GenericDAO<UnidadeEscolar> dao;
private List<UnidadeEscolar> unidades = null;
private String telefone = "";
/** adiciona telefone ao bean */
public void addTelefones(){
//System.out.println(telefone);
bean.addTelefone(telefone);
telefone = "";
}
/** remove telefone do bean */
public void removeTelefone(){
bean.getTelefones().remove(telefone);
telefone = "";
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}

JSF/Primefaces issue when form field rendering depends on selectOneMenu

Form field rendering is depending on selected item in selectOneMenu.
Page:
<h:body>
<f:view>
<h:form>
<h:panelGrid>
<p:inputText value="#{user.username}"/>
<p:selectOneMenu value="#{user.moreInputs}"
required="true">
<p:ajax event="change"
update="moreInputGrid"/>
<f:selectItem itemLabel="" itemValue=""/>
<f:selectItems value="#{user.selectItems}"/>
</p:selectOneMenu>
</h:panelGrid>
<h:panelGrid id="moreInputGrid">
<p:inputText rendered="#{user.renderMoreInputs}"
value="#{user.name}"/>
</h:panelGrid>
<p:commandButton action="#{user.register}"
value="Register user"/>
</h:form>
</f:view>
</h:body>
Backing bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
#ManagedBean
#ViewScoped
public class User {
private String username;
private MoreInputs moreInputs;
private String name;
public enum MoreInputs {
YES,
NO
}
public boolean isRenderMoreInputs() {
return (moreInputs == MoreInputs.YES);
}
public SelectItem[] getSelectItems() {
SelectItem[] items = new SelectItem[2];
items[0] = new SelectItem(
MoreInputs.YES,
"yes");
items[1] = new SelectItem(
MoreInputs.NO,
"no");
return items;
}
public String register() {
return null;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public MoreInputs getMoreInputs() {
return moreInputs;
}
public void setMoreInputs(MoreInputs moreInputs) {
this.moreInputs = moreInputs;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Issue arrises if the client does page refresh after choosing an item causing form fields to render. Such form fields will not be rendered on page refresh, although they should. Plus, if client then tries to submit form, validation is skipped for those hidden fields and form is successfully processed.
Am I doing something wrong? Is there an elegant solution?

Avoid loading datatable each time when i make an ajax call by clicking on each row

In JSF2 - I see my datatable reloading each time when i make an ajax call by clicking on each column row. Is there a way to stop loading each time i make an ajax call ? This creates problem by resetting my datatable to default values and i get a wrong value back at managed bean.
<h:inputText size="8" id="startDate"
value="#{contactBean.startDate}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:inputText>
<h:outputText> - </h:outputText>
<h:inputText size="8" id="endDate" value="#{contactBean.endDate}">
<f:convertDateTime pattern="MM/dd/yyyy" type="date" />
</h:inputText>
<h:commandButton value="Filter"
actionListener="#{contactBean.loadAJAXFilterContentList}">
<f:ajax render=":form1:tableContents" />
</h:commandButton>
<h:dataTable id="tableContents"
value="#{contactBean.filterContentList}" var="crs"
binding="#{contactBean.dataTable}" border="1">
<h:column>
<f:facet name="header">
<h:outputText styleClass="contactTableHeader" value="Date/Time" />
</f:facet>
<h:commandLink action="#{contactBean.loadPreviewScreenContents(crs)}">
<h:outputText title="#{crs.dateTime}" value="#{crs.dateTime}">
<f:convertDateTime pattern="MM/dd/yyyy hh:mm a" type="date" />
</h:outputText>
<f:ajax render=":form1:previewScreen" />
</h:commandLink>
</h:column>
</h:dataTable>
<h:panelGrid id="previewScreen">
<h:outputText styleClass="PreviewHeader"
value="Preview of #{contactBean.previewCntDateTime}" />
</h:panelGrid>
So in the above case whenever i click the column it calls the filterContentList() method in my managed bean instead of calling loadPreviewScreenContents(crs) directly.
My bean is RequestScoped. I tried with SessionScope,ViewScope but these 2 scopes retain my previous states like i have other ajax functions in my page and it retains that state. So i cant use Session or ViewScopes in this case.
Is there a solution ?
Bean code:
#ManagedBean(name = "contactBean")
#RequestScoped
public class ContactManagedBean implements Serializable {
private static final long serialVersionUID = 1L;
List<ContactResponseBean> filterContentList = new ArrayList<ContactResponseBean>();
ContactRequestBean contactRequestBean = new ContactRequestBean();
ContactResponseBean crs = new ContactResponseBean();
private String logText;
HtmlDataTable dataTable;
public void setFilterContentList(List<ContactResponseBean> filterContentList) {
this.filterContentList = filterContentList;
}
public void setFilterContentList(List<ContactResponseBean> filterContentList) {
this.filterContentList = filterContentList;
}
public Date getPreviewCntDateTime() {
return previewCntDateTime;
}
public void setPreviewCntDateTime(Date previewCntDateTime) {
this.previewCntDateTime = previewCntDateTime;
}
public String getLogText() {
return logText;
}
public void setLogText(String logText) {
this.logText = logText;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public ContactResponseBean getCrs() {
return crs;
}
public void setCrs(ContactResponseBean crs) {
this.crs = crs;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public void loadAJAXFilterContentList() {
filterButtonAjxFlag = true;
}
public List<ContactResponseBean> getFilterContentList() {
ContactRequestBean contactRequestBean = new ContactRequestBean();
contactRequestBean.setUserId(getUserId());
contactRequestBean.setSummaryType(getSummaryType());
contactRequestBean.setStartDate(getStartDate());
contactRequestBean.setEndDate(getEndDate());
ContactRequestBeanService crbs = new ContactRequestBeanService();
filterContentList = crbs.getFilterContentList(contactRequestBean);
return filterContentList;
}
public void loadPreviewScreenContents(){
crs = (ContactResponseBean) dataTable.getRowData();
setPreviewCntDateTime(crs.getDateTime());
}
}

Setters don't get called when I use view parameters

I am using JSF 2.1.1. I have a sample JSF page that is used to post country comments. I use the f:viewparam tag to select country pages. Here is the code:
country.xhtml:
<f:metadata>
<f:viewParam name="country" value="#{countryBean2.selectedCountry}" converter="countryConverter" />
</f:metadata>
<h:head>
<title>Country</title>
</h:head>
<h:body>
<h:form id="form">
<h:outputText value="#{countryBean2.selectedCountry.countryName}" />
<br/><br/>
<h:outputText value="Comment:" />
<h:inputText value="#{countryBean2.comment}" />
<br/>
<h:commandButton value="Send">
<f:ajax listener="#{countryBean2.sendComment}" render="form" />
</h:commandButton>
</h:form>
</h:body>
CountryBean2.java:
#Named("countryBean2")
#SessionScoped
public class CountryBean2 implements Serializable {
private EntityCountry selectedCountry;
private String comment;
public EntityCountry getSelectedCountry() { return selectedCountry; }
public void setSelectedCountry(EntityCountry newValue) { selectedCountry = newValue; }
public String getComment() { return comment; }
public void setComment(String newValue) { comment = newValue; }
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
public void sendComment() {
EntityManager em = emf.createEntityManager();
try {
FacesMessage msg = null;
EntityTransaction entr = em.getTransaction();
boolean committed = false;
entr.begin();
try {
EntityCountryComment c = new EntityCountryComment();
c.setCountry(selectedCountry);
c.setComment(comment);
em.persist(c);
committed = true;
msg = new FacesMessage();
msg.setSeverity(FacesMessage.SEVERITY_INFO);
msg.setSummary("Comment was sended");
} finally {
if (!committed) entr.rollback();
}
} finally {
em.close();
}
}
}
CountryConverter.java:
public class CountryConverter implements Converter {
public static EntityCountry country = new EntityCountry();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
#Override
public EntityCountry getAsObject(FacesContext context, UIComponent component, String value) {
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("SELECT c FROM EntityCountry c WHERE c.countryName = :countryName")
.setParameter("countryName", value);
country = (EntityCountry) query.getSingleResult();
return country;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
EntityCountry c = (EntityCountry) value;
return c.getCountryName();
}
}
I can open a country pages successfully (for example http://localhost:8080/test/faces/country.xhtml?country=england), but when I try to post a comment using the commandButton, the setComment setter is not called and the comment variable remains null. I tried to set immediate="true" on both inputText and commandButton, it does not work.
The execute attribute of <f:ajax> defaults to #this, the current component. If you want to submit the entire form, then you need #form instead. Use this in the render as well.
<h:commandButton value="Send">
<f:ajax execute="#form" listener="#{countryBean2.sendComment}" render="#form" />
</h:commandButton>

Resources