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

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.

Related

How to bean-validate a collection property in a jsf composite component, constraints do not fire

How do I define a jsf composite component properly such that its value gets bean-validated correctly in the case it contains a collection?
We have an entity that references a collection of details. Both are annotated with bean-validation-constraints. Please note the annotations at the details-property.
public class Entity implements Serializable {
#NotEmpty
private String name;
#NotEmpty
#UniqueCategory(message="category must be unique")
private List<#Valid Detail> details;
/* getters/setters */
}
public class Detail implements Serializable {
#Pattern(regexp="^[A-Z]+$")
private String text;
#NotNull
private Category category;
/* getters/setters */
}
public class Category implements Serializable {
private final int id;
private final String description;
Category(int id, String description) {
this.id = id;
this.description = description;
}
/* getters/setters */
}
public class MyConstraints {
#Target({ ElementType.TYPE, ElementType.FIELD })
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = UniqueCategoryValidator.class)
#Documented
public static #interface UniqueCategory {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public static class UniqueCategoryValidator implements ConstraintValidator<UniqueCategory, Collection<Detail>> {
#Override
public boolean isValid(Collection<Detail> collection, ConstraintValidatorContext context) {
if ( collection==null || collection.isEmpty() ) {
return true;
}
Set<Category> set = new HashSet<>();
collection.forEach( d-> set.add( d.getCategory() ));
return set.size() == collection.size();
}
public void initialize(UniqueCategory constraintAnnotation) {
// intentionally empty
}
}
private MyConstraints() {
// only static stuff
}
}
The entity can be edited in a jsf-form, where all the tasks concerning the details are encapsulated in a composite component, eg
<h:form id="entityForm">
<h:panelGrid columns="3">
<p:outputLabel for="#next" value="name"/>
<p:inputText id="name" value="#{entityUiController.entity.name}"/>
<p:message for="name"/>
<p:outputLabel for="#next" value="details"/>
<my:detailsComponent id="details" details="#{entityUiController.entity.details}"
addAction="#{entityUiController.addAction}"/>
<p:message for="details"/>
<f:facet name="footer">
<p:commandButton id="saveBtn" value="save"
action="#{entityUiController.saveAction}"
update="#form"/>
</f:facet>
</h:panelGrid>
</h:form>
where my:detailsComponent is defined as
<ui:component xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:p="http://primefaces.org/ui"
>
<cc:interface>
<cc:attribute name="details" required="true" type="java.lang.Iterable"/>
<cc:attribute name="addAction" required="true" method-signature="void action()"/>
</cc:interface>
<cc:implementation>
<p:outputPanel id="detailsPanel">
<ui:repeat id="detailsContainer" var="detail" value="#{cc.attrs.details}">
<p:inputText id="text" value="#{detail.text}" />
<p:message for="text"/>
<p:selectOneMenu id="category" value="#{detail.category}"
converter="#{entityUiController.categoriesConverter}"
placeholder="please select" >
<f:selectItem noSelectionOption="true" />
<f:selectItems value="#{entityUiController.categoryItems}"/>
</p:selectOneMenu>
<p:message for="category"/>
</ui:repeat>
</p:outputPanel>
<p:commandButton id="addDetailBtn" value="add" action="#{cc.attrs.addAction}"
update="detailsPanel" partialSubmit="true" process="#this detailsPanel"/>
</cc:implementation>
</ui:component>
and the EntityUiController is
#Named
#ViewScoped
public class EntityUiController implements Serializable {
private static final Logger LOG = Logger.getLogger( EntityUiController.class.getName() );
#Inject
private CategoriesBoundary categoriesBoundary;
#Valid
private Entity entity;
#PostConstruct
public void init() {
this.entity = new Entity();
}
public Entity getEntity() {
return entity;
}
public void saveAction() {
LOG.log(Level.INFO, "saved entity: {0}", this.entity );
}
public void addAction() {
this.entity.getDetails().add( new Detail() );
}
public List<SelectItem> getCategoryItems() {
return categoriesBoundary.getCategories().stream()
.map( cat -> new SelectItem( cat, cat.getDescription() ) )
.collect( Collectors.toList() );
}
public Converter<Category> getCategoriesConverter() {
return new Converter<Category>() {
#Override
public String getAsString(FacesContext context, UIComponent component, Category value) {
return value==null ? null : Integer.toString( value.getId() );
}
#Override
public Category getAsObject(FacesContext context, UIComponent component, String value) {
if ( value==null || value.isEmpty() ) {
return null;
}
try {
return categoriesBoundary.findById( Integer.valueOf(value).intValue() );
} catch (NumberFormatException e) {
throw new ConverterException(e);
}
}
};
}
}
When we now press the save-button in the above h:form, the name-inputText is validated correctly but the #NotEmpty- and #UniqueCategory-constraint on the details-property are ignored.
What am I missing?
We are on java-ee-7, payara 4.
After diving into this a bit we endet up with a solution using a backing component ValidateListComponent. It was inspired by UIValidateWholeBean and WholeBeanValidator.
That component extends from UIInput and overrides the validation-Methods to operate on a clone of the above details-collection which gets populated with the already validated values of the children-UIInput. Seems to work for now.
<ui:component ...>
<cc:interface componentType="validatedListComponent">
<cc:attribute name="addAction" required="true" method-signature="void action()"/>
</cc:interface>
<cc:implementation>
... see above ...
</cc:implementation>
</ui:component>
with the backing component defined as
#FacesComponent(value = "validatedListComponent")
#SuppressWarnings("unchecked")
public class ValidatedListComponent extends UIInput implements NamingContainer {
#Override
public String getFamily() {
return "javax.faces.NamingContainer";
}
/**
* Override {#link UIInput#processValidators(FacesContext)} to switch the order of
* validation. First validate this components children, then validate this itself.
*/
#Override
public void processValidators(FacesContext context) {
// Skip processing if our rendered flag is false
if (!isRendered()) {
return;
}
pushComponentToEL(context, this);
for (Iterator<UIComponent> i = getFacetsAndChildren(); i.hasNext(); ) {
i.next().processValidators(context);
}
if (!isImmediate()) {
Application application = context.getApplication();
application.publishEvent(context, PreValidateEvent.class, this);
executeValidate(context);
application.publishEvent(context, PostValidateEvent.class, this);
}
popComponentFromEL(context);
}
/**
* Override {#link UIInput#validate(FacesContext)} to validate a cloned collection
* instead of the submitted value.
*
* Inspired by {#link UIValidateWholeBean} and {#link WholeBeanValidator}.
*/
#Override
public void validate(FacesContext context) {
AreDetailsValidCallback callback = new AreDetailsValidCallback();
visitTree( VisitContext.createVisitContext(context)
, callback
);
if ( callback.isDetailsValid() ) {
Collection<?> clonedValue = cloneCollectionAndSetDetailValues( context );
validateValue(context, clonedValue);
}
}
/**
* private method copied from {#link UIInput#executeValidate(FacesContext)}.
* #param context
*/
private void executeValidate(FacesContext context) {
try {
validate(context);
} catch (RuntimeException e) {
context.renderResponse();
throw e;
}
if (!isValid()) {
context.validationFailed();
context.renderResponse();
}
}
private Collection<Object> cloneCollectionAndSetDetailValues(FacesContext context) {
ValueExpression collectionVE = getValueExpression("value");
Collection<?> baseCollection = (Collection<?>) collectionVE.getValue(context.getELContext());
if ( baseCollection==null ) {
return null;
}
// Visit all the components children to find their already validated values.
FindDetailValuesCallback callback = new FindDetailValuesCallback(context);
this.visitTree( VisitContext.createVisitContext(context)
, callback
);
// Clone this components value and put in all cloned details with validated values set.
try {
Collection<Object> clonedCollection = baseCollection.getClass().newInstance();
for( Entry<Object,Map<String,Object>> entry : callback.getDetailSubmittedData().entrySet() ) {
Object clonedDetail = cloneDetailAndSetValues( entry.getKey(), entry.getValue() );
clonedCollection.add( clonedDetail );
}
return clonedCollection;
} catch ( Exception e ) {
throw new ConverterException(e);
}
}
private <T> T cloneDetailAndSetValues(T detail, Map<String, Object> propertyMap) throws Exception {
T clonedDetail = clone(detail);
// check the properties we have in the detail
Map<String, PropertyDescriptor> availableProperties = new HashMap<>();
for (PropertyDescriptor propertyDescriptor : getBeanInfo(detail.getClass()).getPropertyDescriptors()) {
availableProperties.put(propertyDescriptor.getName(), propertyDescriptor);
}
// put their value (or local value) into our clone
for (Map.Entry<String, Object> propertyToSet : propertyMap.entrySet()) {
availableProperties.get(propertyToSet.getKey()).getWriteMethod().invoke(clonedDetail,
propertyToSet.getValue());
}
return clonedDetail;
}
private static <T> T clone(T object) throws Exception {
// clone an object using serialization.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
out.writeObject(object);
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(byteArrayInputStream);
return (T) in.readObject();
}
private class FindDetailValuesCallback implements VisitCallback {
private final FacesContext context;
private final Map<Object, Map<String, Object>> detailSubmittedData = new HashMap<>();
public FindDetailValuesCallback(final FacesContext context) {
this.context = context;
}
final Map<Object, Map<String, Object>> getDetailSubmittedData() {
return detailSubmittedData;
}
#Override
public VisitResult visit(VisitContext visitContext, UIComponent component) {
if ( isVisitorTarget(component) ) {
ValueExpression ve = component.getValueExpression("value");
Object value = ((EditableValueHolder)component).getValue();
if (ve != null) {
ValueReference vr = ve.getValueReference(context.getELContext());
String prop = (String)vr.getProperty();
Object base = vr.getBase();
Map<String, Object> propertyMap
= Optional.ofNullable( detailSubmittedData.get(base) )
.orElseGet( HashMap::new );
propertyMap.put(prop, value );
detailSubmittedData.putIfAbsent( base, propertyMap);
}
}
return ACCEPT;
}
}
private class AreDetailsValidCallback implements VisitCallback {
private boolean detailsValid;
public AreDetailsValidCallback() {
this.detailsValid = true;
}
public boolean isDetailsValid() {
return detailsValid;
}
#Override
public VisitResult visit(VisitContext visitContext, UIComponent component) {
if ( isVisitorTarget(component) ) {
if ( !((EditableValueHolder)component).isValid() ) {
this.detailsValid = false;
}
}
return ACCEPT;
}
}
private boolean isVisitorTarget( UIComponent component ) {
return component instanceof EditableValueHolder && component.isRendered()
&& component!=ValidatedListComponent.this;
}
}
UPDATE: sometimes it is a problem to obtain the ValueReference in FindDetailValuesCallback#visit. The answer given by Michele here solved that problem.

Passing additional Objects to commandLink

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

Update variable retrieved form the database after submitting

I have 2 classes Games and Fouls, there are lot of fouls in a game. The user sends a parameter with the game id to find the game he want and after that the currentGame variable is created.Its type is Game. I have a datatable which prints the fouls in the current game
The setCurentGame setter is called form the body of the page onload.
so far everything works okay, but when I add a new foul, is not added to the datatable, my assumption is that the game was already retrieved (because current game was created before) so the new foul is in the database and not in the Game currentGame.
Is there any way that i can update the currentGame every time a foul i added?
I have tried refreshing the page and even to call the seeter again after creating the foul but nothing worked
The datatable looks like this:
<p:dataTable id="datalist" value="#{gameController.currentGame.foulCollection}" var="item">
<f:facet name="{exporters}">
</f:facet>
<p:ajax event="rowSelect" update="createButton viewButton editButton deleteButton"/>
<p:ajax event="rowUnselect" update="createButton viewButton editButton deleteButton"/>
<p:column width="32" sortBy="#{item.id}" filterBy="#{item.id}">
<f:facet name="header">
<h:outputText value="#{bundle.ListFoulTitle_id}"/>
</f:facet>
<h:outputText value="#{item.id}"/>
</p:column>
<p:column sortBy="#{item.quarter}" filterBy="#{item.quarter}">
<f:facet name="header">
<h:outputText value="#{bundle.ListFoulTitle_quarter}"/>
</f:facet>
<h:outputText value="#{item.quarter}"/>
</p:column>
<p:column sortBy="#{item.foultime}" filterBy="#{item.foultime}">
<f:facet name="header">
<h:outputText value="#{bundle.ListFoulTitle_foultime}"/>
</f:facet>
<h:outputText value="#{item.foultime}"/>
</p:column>
<f:facet name="footer">
<p:commandButton id="createButton" icon="ui-icon-plus" value="#{bundle.Create}" actionListener="#{foulController.prepareCreate}" update=":FoulCreateForm" oncomplete="PF('FoulCreateDialog').show()"/>
</f:facet>
</p:dataTable>
GameController bean:
package onisiforos.fouls.classes;
import onisiforos.fouls.db.Game;
import onisiforos.fouls.classes.util.JsfUtil;
import onisiforos.fouls.classes.util.JsfUtil.PersistAction;
import onisiforos.fouls.bean.GameFacade;
import java.io.Serializable;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
#Named("gameController")
#SessionScoped
public class GameController implements Serializable {
#EJB
private onisiforos.fouls.bean.GameFacade ejbFacade;
private List<Game> items = null;
private Game selected;
private Game currentGame;
public Game getCurrentGame() {
return currentGame;
}
public void setCurrentGame() {
int gid =
Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("gameid"));
Game cg = getGame(gid);
this.currentGame = cg;
}
public GameController() {
}
public Game getSelected() {
return selected;
}
public void setSelected(Game selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private GameFacade getFacade() {
return ejbFacade;
}
public Game prepareCreate() {
selected = new Game();
initializeEmbeddableKey();
return selected;
}
public void create() {
setCurrentGame()
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("GameCreated"));
updateCurrentGame();
if (!JsfUtil.isValidationFailed()) {
items = null;
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("GameUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("GameDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null;
}
}
public List<Game> getGames() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public Game getGame(java.lang.Integer id) {
return getFacade().find(id);
}
public List<Game> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<Game> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
#FacesConverter(forClass = Game.class)
public static class GameControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
GameController controller = (GameController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "gameController");
return controller.getGame(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Game) {
Game o = (Game) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Game.class.getName()});
return null;
}
}
}
}
It seems your setCurrentGame method will not be called, you can manually call it in your create() method to update the current game object from the database after the foul is created.

how can i call setter without calling <f:viewparam> converter?

i am using jsf 2.1.1 and primefaces 3.0.M4. i have a sample jsf page that used to post country comments. i use f:viewparam tag with converter to view country pages. here are the codes:
country.xhtml:
<f:metadata>
<f:viewParam name="country" value="#{countryBean2.selectedCountry}" converter="countryConverter" required="true"/>
</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/>
<p:commandButton value="Send" action="#{countryBean2.sendComment}" update="#this" />
</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 want to call "setComment" setter without calling CountryConverter, when i am using commandbutton to post comment. how can i do that ?
Unfortunately, that's by design of the <f:viewParam> component. It will convert the request parameter and set the property on every HTTP request, also on postbacks. In order to change this behaviour, you would need to extend <f:viewParam> with a custom component which doesn't remember the initial request parameter in its state. It's relatiely simple, instead of delegating the setSubmittedValue() and getSubmittedValue() to StateHelper, you just need to make it an instance variable. This is described in detail in this blog.
#FacesComponent("com.my.UIStatelessViewParameter")
public class UIStatelessViewParameter extends UIViewParameter {
private String submittedValue;
#Override
public void setSubmittedValue(Object submittedValue) {
this.submittedValue = (String) submittedValue;
}
#Override
public String getSubmittedValue() {
return submittedValue;
}
}
OmniFaces has an ready-to-use component for this in flavor of <o:viewParam>. Here is the live example.

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>
...

Resources