how to update selectOneMenu when another one changes in jsf - jsf

i know that this is quetion is already answered here but i don't know why my code didn't work
i have two list and i want that when the first one changes that's the others update
here's my code
<h:selectOneMenu id="e4" styleClass="col-md-5" value="#{categoryModel.selectedMenu}">
<f:selectItem />
<f:selectItems value="#{categoryModel.catFinanceVect}" var="catFinance"itemLabel="#{catFinance.designation}" itemValue="#{catFinance.ligne}" />
<!-- <a4j:ajax event="valueChange" render="e3" execute="#this" />-->
<f:ajax event="valueChange" execute="#this" render="e3" listener="#{categoryModel.getCatItList}"/>
</h:selectOneMenu>
<div class="col-md-1"></div>
<h:selectOneMenu id="e3" styleClass="col-md-6">
<f:selectItem />
<f:selectItems value="#{categoryModel.catItVect}" var="catIt"itemLabel="#{catIt.designation}" itemValue="#{catIt.designation}" />
</h:selectOneMenu>
and here's my backing bean :
#ManagedBean
#SessionScoped
public class CategoryModel {
private CatFinance catFinance= new CatFinance();
private Vector<CatFinance> catFinanceVect = new Vector<CatFinance>();
private CatIt catIt= new CatIt();
private Vector<CatIt> catItVect = new Vector<CatIt>();
private Integer selectedMenu;
public CategoryModel() {
super();
// TODO Auto-generated constructor stub
}
public CatFinance getCatFinance() {
return catFinance;
}
public void setCatFinance(CatFinance catFinance) {
this.catFinance = catFinance;
}
public Vector<CatFinance> getCatFinanceVect() {
return catFinanceVect;
}
public void setCatFinanceVect(Vector<CatFinance> catFinanceVect) {
this.catFinanceVect = catFinanceVect;
}
public CatIt getCatIt() {
return catIt;
}
public void setCatIt(CatIt catIt) {
this.catIt = catIt;
}
public Vector<CatIt> getCatItVect() {
return catItVect;
}
public void setCatItVect(Vector<CatIt> catItVect) {
this.catItVect = catItVect;
}
public Integer getSelectedMenu() {
return selectedMenu;
}
public void setSelectedMenu(Integer selectedMenu) {
this.selectedMenu = selectedMenu;
}
public void getCatFinanceList(){
this.setCatFinance(new CatFinance());
CatFinanceService catFinanceService = (CatFinanceService) SpringDaoCtxFactory.getDaoContext().getBean("CatFinanceService");
this.getCatFinanceVect().clear();
try {
this.getCatFinanceVect().addAll(catFinanceService.getCatFinanceList());
} catch (Exception e) {
e.printStackTrace();
}
}
public void getCatItList(AjaxBehaviorEvent event){
this.setCatIt(new CatIt());
CatItService catItService = (CatItService) SpringDaoCtxFactory.getDaoContext().getBean("CatItService");
this.getCatItVect().clear();
System.out.println("aaaa");
try {
this.getCatItVect().addAll(catItService.getCatItList(2));
} catch (Exception e) {
e.printStackTrace();
}
}
#PostConstruct
public void init(){
getCatFinanceList();
}
}
if anyone can help in this or give me a good tutoriel of how to do it i will appreciate it so much
thanks in advance

The f:ajax event is invalid. It should be change (or empty as it defaults to change for h:selectOneMenu.)
<f:ajax execute="#this" render="e3" listener="#{categoryModel.getCatItList}"/>

Related

jsf primefaces download file in dilogue box is not working

I want to download file in my jsf page, and below is my jsf page
<h:form id="MyListForm">
<p:commandButton value="Attachments" icon="ui-icon-transferthick-e-w" actionListener="#{myTeam.downloadImageDialogue}"
style="font-size: 10px;font-weight: bolder;vertical-align: text-bottom;width: 80px;" >
</p:commandButton>
</h:form>
and my bean code is:
public void downloadImageDialogue() {
RequestContext.getCurrentInstance().openDialog("AttachmentDialog");
}
and my dilogue xhtml page is:
<h:body>
<h:form>
<p:dataTable var="Attachment" value="#{attachmentDialogView.attachmentList}" rows="10">
<p:column headerText="File Name">
<h:outputText value="#{Attachment.fileName}" />
</p:column>
<p:column headerText="Download Attachment">
<p:commandLink ajax="false" id="dwldLink" action="#{attachmentDialogView.downloadImage}">
<f:setPropertyActionListener value="#{Attachment.id.itemId}" target="#{attachmentDialogView.imageItemId}" />
<f:setPropertyActionListener value="#{Attachment.fileName}" target="#{attachmentDialogView.fileName}" />
<f:setPropertyActionListener value="#{Attachment.id.callId}" target="#{attachmentDialogView.callID}" />
<p:graphicImage value="images/dnld1.png" width="25" height="25"/>
<p:fileDownload value="#{attachmentDialogView.file}"/>
</p:commandLink>
</p:column>
</p:dataTable>
</h:form>
</h:body>
and bean code is:
#ManagedBean(name = "attachmentDialogView")
#ViewScoped
public class AttachmentDialogView implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Attachment> attachmentList;
private String imageItemId;
private String fileName;
private DefaultStreamedContent file;
String callID;
#ManagedProperty("#{myTeamService}")
private MyTeamService service;
#PostConstruct
public void init() {
attachmentList = service.getAttachmentList(service.getCallId());
}
public void downloadImage() {
Session session = HibernateUtil.getSessionFactory().openSession();
Attachment attachment = null;
byte[] bImage;
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
try {
if (getCallID() == null || getCallID().equals("")) {
RequestContext.getCurrentInstance().execute("PF('check_dialog').show()");
} else {
attachment = (Attachment) session.createCriteria(Attachment.class).add(Restrictions.eq("id.itemId", getImageItemId())).add(Restrictions.eq("id.callId", getCallID())).uniqueResult();
bImage = attachment.getFileData();
InputStream stream = new ByteArrayInputStream(bImage);
file = new DefaultStreamedContent(stream,externalContext.getMimeType(getFileName()),getFileName());
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
session.close();
}
}
public List<Attachment> getAttachmentList() {
return attachmentList;
}
public void setAttachmentList(List<Attachment> attachmentList) {
this.attachmentList = attachmentList;
}
public MyTeamService getService() {
return service;
}
public void setService(MyTeamService service) {
this.service = service;
}
public String getImageItemId() {
return imageItemId;
}
public void setImageItemId(String imageItemId) {
this.imageItemId = imageItemId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public DefaultStreamedContent getFile() {
return file;
}
public void setFile(DefaultStreamedContent file) {
this.file = file;
}
public String getCallID() {
return callID;
}
public void setCallID(String callID) {
this.callID = callID;
}
}
here dilogue opens correctly but image will not opened please help me.

select one menu doesn't fill the value

I'm using primefaces 4.0.7 .I used selectonemenu,this menu showed the variables however value was null in Bean.Is there any configuration can i do?
Here is part of xhtml code;
<h:outputText value="#{etiketler.kullaniciTipi} : " />
<p:selectOneMenu id="kullaniciTipi" style="width:200px" value="#{kullaniciIslemleriBean.userRole}" >
<f:selectItems value="#{enumBean.kullaniciTipiValues}" var="kullaniciTipi"
itemLabel="#{kullaniciTipi.name}" itemValue="#{kullaniciTipi}" />
</p:selectOneMenu>
here is part of kullaniciIslemleriBean code;
private EnumBase.KullaniciTipi userRole;
public void Kaydet() {
if (userRole == null) {
System.out.println("null value");
return;
}
...
}
public EnumBase.KullaniciTipi getUserRole() {
return userRole;
}
public void setUserRole(EnumBase.KullaniciTipi userRole) {
this.userRole = userRole;
}
Try storing it as String, it will work fine. If you want to store it
as Enum then try converter
<h:outputText value="#{etiketler.kullaniciTipi} : " />
<p:selectOneMenu id="kullaniciTipi" style="width:200px" value="#{kullaniciIslemleriBean.userRole}" >
<f:selectItems value="#{enumBean.kullaniciTipiValues}" var="kullaniciTipi"
itemLabel="#{kullaniciTipi.name}" itemValue="#{kullaniciTipi.name}" />
</p:selectOneMenu>
private String userRole;
public void Kaydet() {
if (userRole == null) {
System.out.println("null value");
return;
}
...
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}

Why I can't put the value as {zdsqlBean.thszfas} in jsf?

When I put the value as {zdsqlBean.zdljs}, I can get the result which I want.
<h:outputLabel value="#{msgs.zdlj}" style="font-weight:bold" />
<p:selectOneMenu id="zdlj2" value="#{zsjBean.zdlj}">
<f:selectItems value="#{zdsqlBean.zdljs}" var="bll4"
itemLabel="#{bll4.descri}" itemValue="#{bll4.value}" />
</p:selectOneMenu>
But when I put the value as {zdsqlBean.thszfas}, I can't get the result which I want.
<h:outputLabel value="#{msgs.zdlj}" style="font-weight:bold" />
<p:selectOneMenu id="zdlj2" value="#{zsjBean.zdlj}">
<f:selectItems value="#{zdsqlBean.thszfas}" var="bll4"
itemLabel="#{bll4.descri}" itemValue="#{bll4.value}" />
</p:selectOneMenu>
Why? The following is the zdsqlBean:
#ManagedBean(name = "zdsqlBean")
#SessionScoped
public class ZdsqlBean {
private List<Zdsql> zdsqls;
private List<Zdsql> zdljs;
private List<Zdsql> thszfas;
public ZdsqlBean(){
this.genzdljs();
this.getThszfas();
}
public List<Zdsql> getZdsqls() {
return zdsqls;
}
public List<Zdsql> getThszfas() {
System.out.println("zdsqls1==");
return thszfas;
}
public List<Zdsql> getZdljs() {
return zdljs;
}
public void genzdljs() {
try {
String queryString = "select m from Zdsql m where m.filter = :filter Order by m.id";
TypedQuery<Zdsql> query = DBDAO.getEntityManager().createQuery(
queryString, Zdsql.class);
query.setParameter("filter", "zdlj");
System.out.println("zdsqls1==");
zdljs = query.getResultList();
} catch (Exception re) {
DBDAO.log("genzdljs() failed", Level.SEVERE, re);
}
}
public void genthszfas() {
try {
System.out.println("zdsqls1`1==");
String queryString = "select m from Zdsql m where m.filter = :filter Order by m.id";
TypedQuery<Zdsql> query = DBDAO.getEntityManager().createQuery(
queryString, Zdsql.class);
query.setParameter("filter", "thszfas");
System.out.println("zdsqls12==");
thszfas = query.getResultList();
} catch (Exception re) {
DBDAO.log("genthszfas() failed", Level.SEVERE, re);
}
}
}
You're not populating your second list. Your constructor should look like:
public ZdsqlBean(){
this.genzdljs();
this.genthszfas(); //and not this.getThszfas();
}
Luiggi Mendoza is right. Use understandable names if you want to avoid errors like this!!

JSF UIRepeat and PostBack

I have a simple page where a I use <ui:repeat> and it gets the value from a backing bean.
The initial request will give it an empty list. The postback then will invoke an action that will change the model behind the <ui:repeat> but it is not rendered?!
I debugged through it and I saw that the <ui:repeat> evaluates the value at restore view phase but thats it. When it reaches render response it does not use the latest value from my bean. Is that the expected behavior?
How can I make that work? Do I have to write my own repeat tag?
I can't really tell what could be the problem without some of your code, but these are the basics:
Backing bean:
public class ObjectService{
private DataModel objectDataModel;
private List<Object> objectList;
private Pagination paginationHelper;
private ObjectDao objectDao = new ObjectDao();
private String queryOption;
public void setQueryOption(String queryOption){
this.queryOption = queryOption;
}
public String getQueryOption(){
return this.queryOption;
}
public <E> PaginationHelper getPagination(final List<E> list) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return list.size();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(list);
}
};
return pagination;
}
public void setPagination(PaginationHelper pagination) {
this.pagination = pagination;
}
public List<Object> getObjectList(){
this.objectList = objectDao.readObjectsWhere(queryOption);
return this.objectList;
}
public void setObjectList(List<Object> objectList){
this.objectList = objectList;
}
public DataModel getObjectDataModel(){
if (objectDataModel == null) {
objectDataModel = getPagination(getObjectList()).createPageDataModel();
}
return objectDataModel;
}
public void setObjectDataModel(DataModel objectDataModel){
this.objectDataModel = objectDataModel
}
public String changeModel(){
objectDataModel = null;
return null;
}
}
XHTML page:
...
<h:form>
<fieldset>
<label>
<span>Option:</span>
<h:inputText value="#{objectService.queryOption}" />
</label>
<h:commandButton action="#{objectService.changeModel}" value="request data" />
</fieldset>
<ui:repeat value="#{objectService.objectDataModel}" var="objectVar">
<h:outputLabel value="#{objectVar.property1}" />
<h:outputLabel value="#{objectVar.property2}" />
<h:outputLabel value="#{objectVar.property3}" />
</ui:repeat>
</h:form>
...

Changes not reflected in JPA entities after updating in h:dataTable

I am working with Eclipse and Glassfish 3.0. Pretty new to this technology although I have done similar things before. Very simple really got a datatable bound to a backing bean. Add methods and remove methods i have covered - the problem lies with the update method I am calling. I cannot seem to see the changes being picked up in the component (HtmlInputText) never mind passing the data back to the table.
My code for the data table is below (and the jsf page)
<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">
<f:loadBundle basename="resources.application" var="msg"/>
<head>
<title><h:outputText value="#{msg.welcomeTitle}" /></title>
</head>
<body>
<h:form id="mainform">
<h:dataTable var="row" border="0" value="#{beanCategory.collection}" binding="#{beanCategory.datatable}">
<f:facet name="header">
<h:outputText value="Categories"/>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Description"/>
</f:facet>
<h:inputText id="input1" value="#{row.description}" valueChangeListener="#{row.inputChanged}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Id"/>
</f:facet>
<h:outputText id="id" value="#{row.id}"/>
</h:column>
<h:column>
<h:commandButton value="Delete" type="submit" action="#{beanCategory.remove}">
<f:setPropertyActionListener target="#{beanCategory.selectedcategory}" value="#{row}"/>
</h:commandButton>
<h:commandButton value="Save" action="#{beanCategory.update}"
>
<f:setPropertyActionListener
target="#{beanCategory.selectedcategory}" value="#{row}" />
</h:commandButton>
</h:column>
</h:dataTable>
<h:inputText id="text1"></h:inputText> <h:commandButton action="#{beanCategory.addCategory}" value="Add" type="submit" id="submitbutton">
</h:commandButton>
<br/><br/>
Messages
<h:messages></h:messages><br /><br />
</h:form>
</body>
</html>
Backing Bean is here
package net.bssuk.timesheets.controller;
import java.io.Serializable;
import java.util.List;
import javax.faces.component.UIInput;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.persistence.*;
import net.bssuk.timesheets.model.Category;
#javax.inject.Named("beanCategory")
#javax.enterprise.context.SessionScoped
public class BeanCategory implements Serializable {
private List<Category> collection;
private EntityManagerFactory emf;
private EntityManager em;
private int selectedid;
private Category selectedcategory;
private HtmlDataTable datatable;
private static final long serialVersionUID = 1L;
public BeanCategory() {
// TODO Auto-generated constructor stub
System.out.println("Bean Constructor");
}
public String addCategory() {
try {
this.emf = Persistence.createEntityManagerFactory("timesheets1");
System.out.println("Changed - Now attempting to add");
System.out.println("Ready to do cateogory");
Category category = new Category();
FacesContext context = FacesContext.getCurrentInstance();
UIInput input = (UIInput) context.getViewRoot().findComponent(
"mainform:text1");
String value = input.getValue().toString();
if (value != null) {
category.setDescription(input.getValue().toString());
} else {
category.setDescription("Was null");
}
this.em = this.emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(category);
tx.commit();
em.close();
emf.close();
// return "index.xhtml";
} catch (Exception e) {
e.printStackTrace();
}
return "return.html";
}
public String remove() {
try {
this.emf = Persistence.createEntityManagerFactory("timesheets1");
System.out.println("Getting Collection");
this.em = this.emf.createEntityManager();
FacesContext context = FacesContext.getCurrentInstance();
System.out.println("Number found is " + this.selectedid);
if (selectedcategory != null) {
System.out.println("removing "+selectedcategory.getId()+" - " +selectedcategory.getDescription());
EntityTransaction tx = em.getTransaction();
tx.begin();
System.out.println("Merging..");
this.em.merge(selectedcategory);
System.out.println("removing...");
this.em.remove(selectedcategory);
tx.commit();
em.close();
emf.close();
}else{
System.out.println("Not found");
}
return "index.xhtml";
} catch (Exception e) {
e.printStackTrace();
return "index.xhtml";
}
}
public String update() {
try {
this.emf = Persistence.createEntityManagerFactory("timesheets1");
System.out.println("Update Getting Collection");
Category category = (Category) getDatatable().getRowData();
FacesContext context = FacesContext.getCurrentInstance();
System.out.println("PHASE ID="+context.getCurrentPhaseId().toString());
if (category != null) {
// DESCRIPTION VALUE BELOW IS ALWAYS OLD VALUE (IE DATA IN DATABASE)
System.out.println("updating "+category.getId()+" - " +category.getDescription());
this.em = this.emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.merge(category);
tx.commit();
em.close();
emf.close();
}else{
System.out.println("Not found");
}
return "index.xhtml";
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public void setCollection(List<Category> collection) {
this.collection = collection;
}
public List<Category> getCollection() {
// this.emf=Persistence.createEntityManagerFactory("timesheets1");
// System.out.println("Getting Collection");
try {
this.emf = Persistence.createEntityManagerFactory("timesheets1");
this.em = this.emf.createEntityManager();
Query query = this.em.createNamedQuery("findAll");
this.collection = query.getResultList();
return this.collection;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void setSelectedid(int id) {
this.selectedid=id;
}
public void setSelectedcategory(Category selectedcategory) {
this.selectedcategory = selectedcategory;
}
public HtmlDataTable getDatatable() {
return datatable;
}
public void setDatatable(HtmlDataTable datatable) {
this.datatable = datatable;
}
public Category getSelectedcategory() {
return selectedcategory;
}
}
My Mapped entity for JPA is here
package net.bssuk.timesheets.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the CATEGORIES database table.
*
*/
#Entity
#Table(name="CATEGORIES")
#NamedQuery(name="findAll", query = "SELECT c from Category c")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
private String description;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
public Category() {
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
OK - Updated my code to follow example. I have tried to incorporate an EJB into the scenario as follows
package net.bssuk.timesheets.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import net.bssuk.timesheets.model.Category;
#Stateless
public class CategoryEJB implements CategoryEJBRemote {
#PersistenceContext(unitName="timesheets1")
private EntityManager em;
#Override
public List<Category> findCategories() {
// TODO Auto-generated method stub
System.out.println("find categories");
Query query = em.createNamedQuery("findAll");
return query.getResultList();
}
#Override
public Category createCategory(Category category) {
// TODO Auto-generated method stub
em.persist(category);
return category;
}
#Override
public Category udpateCategory(Category category) {
// TODO Auto-generated method stub
return em.merge(category);
}
#Override
public void deleteCategory(Category category) {
// TODO Auto-generated method stub
em.remove(em.merge(category));
}
}
My EJB is below
package net.bssuk.timesheets.ejb;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import net.bssuk.timesheets.model.Category;
#Stateless
public class CategoryEJB implements CategoryEJBRemote {
#PersistenceContext(unitName="timesheets1")
private EntityManager em;
#Override
public List<Category> findCategories() {
// TODO Auto-generated method stub
System.out.println("find categories");
Query query = em.createNamedQuery("findAll");
return query.getResultList();
}
#Override
public Category createCategory(Category category) {
// TODO Auto-generated method stub
em.persist(category);
return category;
}
#Override
public Category udpateCategory(Category category) {
// TODO Auto-generated method stub
return em.merge(category);
}
#Override
public void deleteCategory(Category category) {
// TODO Auto-generated method stub
em.remove(em.merge(category));
}
}
Can anyone suggest if this sort of looks ok? Or have I completely lost the plot with it!
Look,
<h:dataTable var="row" border="0" value="#{beanCategory.collection}" binding="#{beanCategory.datatable}">
and
public List<Category> getCollection() {
// this.emf=Persistence.createEntityManagerFactory("timesheets1");
// System.out.println("Getting Collection");
try {
this.emf = Persistence.createEntityManagerFactory("timesheets1");
this.em = this.emf.createEntityManager();
Query query = this.em.createNamedQuery("findAll");
this.collection = query.getResultList();
return this.collection;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
You're loading the list inside a getter method. This is a very bad idea. A getter should solely be an access point to the bean property, not to do some business job. A getter can be called multiple times during bean's life. The DB will be hit on every call and the local collection property which was been updated by JSF during form submit will be overwritten again at a later point. This makes no sense.
Do the business job in the (post)constructor method or action(listener) methods. Definitely not in a getter. Here's a minimum kickoff example with some code improvements:
<h:dataTable value="#{bean.categories}" var="category">
<h:column>
<h:inputText value="#{category.description}" />
</h:column>
<h:column>
<h:outputText value="#{category.id}" />
</h:column>
<h:column>
<h:commandButton value="Delete" action="#{bean.delete(category)}" />
<h:commandButton value="Save" action="#{bean.update(category)}" />
</h:column>
</h:dataTable>
<h:inputText value="#{bean.newCategory.description}" />
<h:commandButton value="Add" action="#{bean.add}" />
(note that passing arguments in EL is supported since EL 2.2 (part of Servlet 3.0), Glassfish 3 is a Servlet 3.0 container, so it should definitely support it when web.xml is properly declared conform Servlet 3.0 spec)
with
#ManagedBean
#ViewScoped // Definitely don't use session scoped. I'm not sure about CDI approach, so here's JSF example.
public class Bean {
private List<Category> categories;
private Category newCategory;
#EJB
private CategoryService categoryService;
#PostConstruct
public void init() {
categories = categoryService.list();
newCategory = new Category();
}
public void add() {
categoryService.add(newCategory);
init();
}
public void delete(Category category) {
categoryService.delete(category);
init();
}
public void update(Category category) {
categoryService.update(category);
init();
}
public List<Category> getCategories() {
return categories;
}
public Category getNewCategory() {
return newCategory;
}
}
That should be it. See also:
Why JSF calls getters multiple times
Help understanding JSF's multiple calls to managed bean
<h:dataTable value=#{myBean.xxx}>: getXxx() get called so many times, why?
As I see, you have forgotten the <h:form>. This is very necessary to save inputs.

Resources