I have the main page with includes testcomponent1 which inturn includes testcomponent2. Ajax call is in testcomponent2. The call is intiated in the javascript but never hits the controller. If the ajax call is moved into testcomponent1, it triggers the call and makes it to the controller. I am including the test code for your reference.
TESTCONTROLLER:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.AjaxBehaviorEvent;
#ManagedBean
#ViewScoped
public class TestController implements Serializable {
/** <code>serialVersionUID</code> */
private static final long serialVersionUID = -999213365169849345L;
private int customerkey;
private String customerName;
public void processKeyChange(AjaxBehaviorEvent e){
System.out.println("I am in the Ajax method and my value is: " + customerkey);
}
//GETTERS AND SETTERS
public int getCustomerkey() {
return customerkey;
}
public void setCustomerkey(int customerkey) {
this.customerkey = customerkey;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
testPage.xhtml
<ui:define name="searchCriteria">
<h:form id="orderHeaderForm" prependId="false">
<h:panelGroup id="orderDiv" layout="block">
<com:testcomponent1 id="testComponent1"
customerKey="#{testController.customerkey}"
customerName="#{testController.customerName}"/>
</h:panelGroup>
</h:form>
</ui:define>
</ui:composition>
testcomponent1.xhtml
<cc:interface>
<cc:attribute name="customerKey" type="java.lang.Integer" />
<cc:attribute name="customerName" type="java.lang.String" />
</cc:interface>
<cc:implementation>
<h:panelGroup id="#{cc.clientId}" layout="block">
<com:testcomponent2 id="testcomponent2"
key="#{cc.attrs.customerKey}"
name="#{cc.attrs.customerName}" />
</h:panelGroup>
</cc:implementation>
testcomponent2.xhtml
<cc:implementation>
<h:panelGrid id="#{cc.clientId}" columns="2" border="0" cellspacing="0" cellpadding="0">
<h:outputLabel id="customerid" for="txtcustomerKey"/>
<h:inputText id="txtcustomerKey" value="#{cc.attrs.key}" onchange="alert (document.getElementById(this.id).value)">
<f:ajax event="change" listener="#{testController.processKeyChange}" execute="#this" render="txtCustomerName" />
</h:inputText>
<h:outputLabel id="customerName" for="txtCustomerName"/>
<h:outputText value="#{cc.attrs.name}" id="txtCustomerName" />
</h:panelGrid>
</cc:implementation>
thanks
I think the problem is in <h:panelGrid id="#{cc.clientId}"...>. By default, a composite component is an instance of UINamingContainer, so instead do that, you can set an id with any name and use it. A good practice is avoid EL expressions in id field.
You shouldn't reassign #{cc.clientId} as ID of JSF components, but instead as ID of plain vanilla HTML elements such as <span> or <div>.
<span id="#{cc.clientId}">
or
<div id="#{cc.clientId}">
Related
I am facing a problem when trying to export a DataTable with some columns, both the DataTable and the Column components are composite elements, like this:
Custom dataTable XHTML (v:dataTable):
<cc:interface>
<cc:attribute name="value" required="true" />
<cc:attribute name="selectionMode" default="multiple" />
<cc:attribute name="selectionBean" />
<cc:attribute name="selectionProperty" />
<cc:facet name="header" />
</cc:interface>
<cc:implementation>
<p:dataTable id="teste" var="tableItem" value="#{cc.attrs.value}"
selection="#{cc.attrs.selectionBean[cc.attrs.selectionProperty]}"
rowKey="#{tableItem.id}" rowsPerPageTemplate="15, 30, 45"
paginator="true" rows="15"
emptyMessage="#{messages['dataTable.emptyMessage']}">
<cc:insertChildren />
<f:facet name="footer">
<p:commandButton value="#{messages['dataTable.exportExcel']}"
ajax="false">
<p:dataExporter type="xls" target="teste" fileName="export" />
</p:commandButton>`enter code here`
</f:facet>
</p:dataTable>
</cc:implementation>
Custom column XHTML (v:dataColumn):
<cc:interface
componentType="com.example.VDataColumn">
<cc:attribute name="value" />
</cc:interface>
<cc:implementation>
<c:choose>
<c:when test="#{cc.childCount gt 0}">
<cc:insertChildren />
</c:when>
<c:otherwise>
<h:outputText value="#{cc.attrs.value}" />
</c:otherwise>
</c:choose>
</cc:implementation>
The Column component is an extension of the org.primefaces.component.column.Column class:
package com.example.component;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UINamingContainer;
import org.primefaces.component.column.Column;
#FacesComponent("com.example.VDataColumn")
public class VDataColumn extends Column implements NamingContainer {
#Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
}
The DataTable and Column are used as it follows:
<v:dataTable
value="#{testController.resultList}"
selectionBean="#{testController}"
selectionProperty="selectedList" selectionMode="multiple">
<p:column value="#{tableItem.id}" headerText="ID" />
<v:dataColumn value="#{tableItem.code}" headerText="Code" />
<v:dataColumn value="#{tableItem.nome}" headerText="Name" />
<v:dataColumn value="#{tableItem.desc}" headerText="Desc" />
</v:dataTable>
When I try to export the dataTable with the dataExporter that is inside the component, I get just one column in the XLS file, and it is only the p:column.
Debugging the primefaces DataExporter class, i noticed that the DataTable object contains 4 objects in the getChildren() method, one Column and 3 VDataColumn's, and only the Column object contains children itself.
Did anybody have the same issue? I am using Primefaces 4.0
I had same problem with a custom component. We resolve by extending the exporter and using custom validation for the component.
if (component instanceof UINamingContainer) {
UINamingContainer uiNamingContainer = (UINamingContainer) component;
UIComponent panel = uiNamingContainer.getFacet(UIComponent.COMPOSITE_FACET_NAME);
Collection<UIComponent> children = panel.getChildren();
for (UIComponent uiComponent : children) {
if (uiComponent instanceof javax.faces.component.html.HtmlOutputText) {
try {
uiNamingContainer.encodeBegin(context);
return super.exportValue(context, uiComponent);
} catch (IOException e) {
LOGGER.error(e);
} finally {
try {
uiNamingContainer.encodeEnd(context);
} catch (IOException e) {
LOGGER.error(e);
}
}
}
}
}
In my custom component, I have
<composite:interface>
<composite:editableValueHolder name="val_pwd" targets="form:pwd"/>
<composite:attribute name="name" required="true"/>
.....
</composite:interface>
<composite:implementation>
<h:form id="form">
<h:panelGrid columns="3">
<h:outputText value="#{cc.attrs.namePrompt}" />
<h:inputText value="#{cc.attrs.name}" id="name"/>
<h:outputText value="#{cc.attrs.passwordPrompt}" />
<h:inputSecret value="#{cc.attrs.pwd}" id="pwd"/>
<h:commandButton value="#{cc.attrs.submitButtonValue}" action="#{cc.attrs.actionMethod}"/>
</h:panelGrid>
</h:form>
</composite:implementation>
I have a validator,
#FacesValidator("passwordVal")
public class PasswordValidator implements Validator {
public PasswordValidator() {
super();
}
#Override
public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException {
if(object instanceof String){
String s = (String) object;
if(s.contains("#"))
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error","Password cannot have #"));
}
}
}
In my JSF page, I have
<h:body>
<util:ccwithcustomval namePrompt="r_Name" passwordPrompt="r_pwd" name="#{person.name}"
pwd="#{person.pwd}" actionMethod="#{person.action}" submitButtonValue="r_submit">
<f:validateLength for="val_name" maximum="5"/>
<f:validator validatorId="passwordVal" for="val_pwd" />
</util:ccwithcustomval>
</h:body>
However, it fails with exception
InputComponent.xhtml #12,60 <f:validator> ADF_FACES-60085:Parent not an instance of
EditableValueHolder: javax.faces.component.UINamingContainer#4e18afaa
The problem is with my validator, if I comment it out the page displays
Following is my requirement-
Here I have a p:panelGrid which can add & delete the row of table. The grid contains some p:inputText and various other PrimeFaces components along with a p:fileUpload component in each row. The component p:fileUpload is set with mode="advanced" auto="true" attributes, which automatically uploads the file and hide itself after completing the successful upload.
The whole p:panelGrid is in #ViewScoped, hence working fine. I kept p:fileUpload component in #RequestScoped since for each upload request it has to upload the file but after adding new row, the previous state is not persisted anymore. so the p:fileUpload is starting visible in previous rows also. That's what I don't want. Do I need to write any custom scope for it?
Below is the view-|
<h:form>
<p:panel id="agentForm" header="#{msg.AGENTS_INFORMATION}"
style="overflow:auto; margin-bottom: 2px">
<div align="center" style="margin-top: 20px; margin-bottom: 2px">
<ui:repeat value="#{agent.scenarioList}" var="c">
<p:panelGrid>
<p:row>
<p:column>
<p:inputText id="ipaddress" value="#{c.machineIpAddress}"
style="width:90%">
<p:watermark for="ipaddress" value="#{msg.MACHINE_IP_ADDRESS}" />
</p:inputText>
</p:column>
<p:column>
<p:inputText id="username" value="#{c.machineUsername}"
style="width:90%">
<p:watermark for="username" value="#{msg.MACHINE_USERNAME}" />
</p:inputText>
</p:column>
<p:column>
<p:password id="passwd" value="#{c.machinePassword}">
<p:watermark for="passwd" value="#{msg.MACHINE_PASSWORD}" />
</p:password>
</p:column>
<p:column id="fileUpload">
<p:fileUpload rendered="#{!fileUploadController.hidden}"
label="Upload Script" style="font-size: 100% !important;"
showButtons="false"
fileUploadListener="#{fileUploadController.upload}"
mode="advanced" auto="true" sizeLimit="100000"
allowTypes="/(\.|\/)(py|txt)$/"
update="fileUpload, outPanel, :message" />
<p:outputPanel id="outPanel">
<!-- Below outputLabel will be linked to uploaded file, so that User can see the file -->
<p:outputLabel style="cursor: pointer" value="View uploded Script"
label="View Script" rendered="#{fileUploadController.hidden}" />
</p:outputPanel>
</p:column>
<p:column>
<p:inputText id="testname" value="#{c.testName}"
style="width:90%">
<p:watermark for="testname" value="#{msg.TEST_NAME}" />
</p:inputText>
</p:column>
<p:column>
<p:spinner id="threads" value="#{c.threads}" min="1" max="500"
size="8">
<p:tooltip for="threads" value="#{msg.TEST_NAME}"
showEffect="slide" hideEffect="slide" />
</p:spinner>
</p:column>
<p:column>
<p:selectBooleanCheckbox id="chkSelected" value="#{c.selected}">
<p:tooltip for="chkSelected" value="#{msg.CHECKBOX}"
showEffect="slide" hideEffect="slide" />
</p:selectBooleanCheckbox>
</p:column>
</p:row>
</p:panelGrid>
</ui:repeat>
<p:toolbar style="margin-top: 10px;">
<p:toolbarGroup align="right">
<p:commandButton value="#{msg.ADD_IT}"
update=":message, agentForm"
actionListener="#{agent.addComponent()}" />
<p:commandButton value="#{msg.DELETE_IT}"
update=":message, agentForm"
actionListener="#{agent.deleteComponent()}" />
</p:toolbarGroup>
</p:toolbar>
</div>
</p:panel>
</h:form>
My managed bean which is in #ViewScoped look like this-
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.ViewScoped;
import org.ravij.performance.model.Scenario;
#ManagedBean(name = "agent")
#ViewScoped
public class AgentInfo implements Serializable {
private static final long serialVersionUID = 1L;
List<Scenario> scenarioList;
#PostConstruct
public void initBean() {
this.scenarioList = new ArrayList<Scenario>();
this.scenarioList.add(new Scenario());
}
public void addComponent() {
if (this.scenarioList != null) {
this.scenarioList.add(new Scenario());
} else {
this.initBean();
}
}
public void deleteComponent() {
List<Scenario> itemsToDelete = new ArrayList<Scenario>();
if (this.scenarioList != null) {
for (Scenario b : this.scenarioList) {
if (b.isSelected()) {
itemsToDelete.add(b);
}
}
this.scenarioList.removeAll(itemsToDelete);
}
}
public List<Scenario> getScenarioList() {
return scenarioList;
}
public void setScenarioList(List<Scenario> scenarioList) {
this.scenarioList = scenarioList;
}
}
The Scenario object contains all the information of a row. Below is the code-
package org.ravij.performance.model;
import java.io.Serializable;
public class Scenario implements Serializable {
private String machineIpAddress;
private String machineUsername;
private String machinePassword;
private String uploadedFilePath;
private String testName;
private int threads = 1;
private boolean selected = false;
//Below are the getters and setter w.r.t all the above variables
//I am not putting it, to make the code short
}
The managed bean FileUploadController is in #RequestScoped
You should simply keep your hidden attribute with the other values in your #ViewScoped bean. Your current code has a single hidden attribute shared with all your <p:fileUpload components which is probably not what you want.
The behavior looks good because you are only updating the current fileUpload but according to your code all the others <p:fileUpload component are supposed to be hidden.
You should also put your <h:form into your <ui:repeat so that you can know the current line which is concerned by the file being uploaded by putting something like an index (which you can get from the <ui:repeat using varStatus attribute) or any other identifier to match the current line in an hidden input.
From #{fileUploadController.upload} the easiest manner to get the hidden parameter is to get the response from FacesContext as explained here : How to get parametrs to BackingBean from jsf page in <ui:repeat>
UPDATE
It was a bit harder than expected, the problem is that <p:fileUpload will send everything in the enclosing form (didn't try to play with process attribute) and thus it will be hard to know what row is concerned by the file upload.
Also I didn't knew that you couldn't put <h:form in your <ui:repeat but the behavior of your delete button is blocking as it expects to get everything in one form.
I made a working POC using dialog to put the fileupload outside, here is how :
The trivial Scenario.java :
public class Scenario implements Serializable {
private String machineIpAddress;
private String machineUsername;
private String machinePassword;
private String uploadedFilePath;
private String testName;
private int threads = 1;
private boolean selected = false;
private boolean hidden = false; // This is new
// + Getters/Setters
}
A few changes in the AgentInfo.java :
#ManagedBean(name = "agent")
#ViewScoped
public class AgentInfo implements Serializable {
private List<Scenario> scenarioList;
private Scenario currentScenario; // This is new
// I removed the #PostConstruct which I rarely use
public void addComponent() {
if (this.scenarioList != null) {
this.scenarioList.add(new Scenario());
}
}
public void deleteComponent() {
if (this.scenarioList == null) {
return;
}
List<Scenario> itemsToDelete = new ArrayList<Scenario>();
for (Scenario scenario : this.scenarioList) {
if (scenario.isSelected()) {
itemsToDelete.add(scenario);
}
}
this.scenarioList.removeAll(itemsToDelete);
}
// This is new, it must be called before opening the upload dialog
// in order to keep a pointer on the current scenario you are working on
public void prepareUpload(Scenario scenario) {
this.currentScenario = scenario;
}
// I put the upload method here
public void upload(FileUploadEvent event) {
// Do what you need to do here
this.currentScenario.setHidden(true);
RequestContext.getCurrentInstance().execute("uploadDialogWidget.hide()");
}
public List<Scenario> getScenarioList() {
if (this.scenarioList == null) {
this.scenarioList = new ArrayList<Scenario>();
this.scenarioList.add(new Scenario());
}
return scenarioList;
}
public void setScenarioList(List<Scenario> scenarioList) {
this.scenarioList = scenarioList;
}
public Scenario getCurrentScenario() {
return currentScenario;
}
public void setCurrentScenario(Scenario currentScenario) {
this.currentScenario = currentScenario;
}
}
The most changes are in the view, I put a <h:commandButton to open the dialog in the form. I also added the dialog, and added the redisplay attribute for your password fields (which is necessary to have if you want to keep the value after form submission).
Note that I removed references to a component with message id which was not gave, don't forget to reintroduce it.
the .xhtml :
<h:form id="agentForm">
<p:panel header="#{msg.AGENTS_INFORMATION}"
style="overflow:auto; margin-bottom: 2px">
<div align="center" style="margin-top: 20px; margin-bottom: 2px">
<ui:repeat value="#{agent.scenarioList}" var="c">
<p:panelGrid>
<p:row>
<p:column>
<p:inputText id="ipaddress" value="#{c.machineIpAddress}"
style="width:90%">
<p:watermark for="ipaddress" value="#{msg.MACHINE_IP_ADDRESS}" />
</p:inputText>
</p:column>
<p:column>
<p:inputText id="username" value="#{c.machineUsername}"
style="width:90%">
<p:watermark for="username" value="#{msg.MACHINE_USERNAME}" />
</p:inputText>
</p:column>
<p:column>
<p:password id="passwd" value="#{c.machinePassword}" redisplay="true">
<p:watermark for="passwd" value="#{msg.MACHINE_PASSWORD}" />
</p:password>
</p:column>
<p:column id="fileUpload">
<p:commandButton icon="ui-icon-arrowthick-1-n" value="Upload"
actionListener="#{agent.prepareUpload(c)}"
update=":uploadDialog"
oncomplete="uploadDialogWidget.show()"
rendered="#{!c.hidden}" />
<p:outputPanel id="outPanel">
<!-- Below outputLabel will be linked to uploaded file, so that User can see the file -->
<p:outputLabel style="cursor: pointer" value="View uploded Script"
rendered="#{c.hidden}" />
</p:outputPanel>
</p:column>
<p:column>
<p:inputText id="testname" value="#{c.testName}"
style="width:90%">
<p:watermark for="testname" value="#{msg.TEST_NAME}" />
</p:inputText>
</p:column>
<p:column>
<p:spinner id="threads" value="#{c.threads}" min="1" max="500"
size="8">
<p:tooltip for="threads" value="#{msg.TEST_NAME}"
showEffect="slide" hideEffect="slide" />
</p:spinner>
</p:column>
<p:column>
<p:selectBooleanCheckbox id="chkSelected" value="#{c.selected}">
<p:tooltip for="chkSelected" value="#{msg.CHECKBOX}"
showEffect="slide" hideEffect="slide" />
</p:selectBooleanCheckbox>
</p:column>
</p:row>
</p:panelGrid>
</ui:repeat>
<p:toolbar style="margin-top: 10px;">
<p:toolbarGroup align="right">
<p:commandButton value="#{msg.ADD_IT}" update="agentForm"
actionListener="#{agent.addComponent()}" />
<p:commandButton value="#{msg.DELETE_IT}" update="agentForm"
actionListener="#{agent.deleteComponent()}" />
</p:toolbarGroup>
</p:toolbar>
</div>
</p:panel>
</h:form>
<p:dialog id="uploadDialog" widgetVar="uploadDialogWidget" header="File upload">
<h:form rendered="#{!empty agent.currentScenario}">
<p:fileUpload
label="Upload Script" style="font-size: 100% !important;"
showButtons="false"
fileUploadListener="#{agent.upload}"
mode="advanced" auto="true" sizeLimit="100000"
allowTypes="/(\.|\/)(py|txt)$/"
update=":agentForm">
</p:fileUpload>
<p:commandButton value="Cancel" onclick="uploadDialogWidget.hide();" onstart="return false;" />
</h:form>
</p:dialog>
You should consider to move from <p:panelGrid to a <p:dataTable which has a built in mechanism to work with row selection.
i have these simple pages:
list.xhtml
<h:form id="form">
<h:dataTable value="#{testBean.model}" var="elem">
<h:column>
<f:facet name="header">code</f:facet>
#{elem.code}
</h:column>
<h:column>
<f:facet name="header">description</f:facet>
#{elem.description}
</h:column>
<h:column>
<f:facet name="header">action</f:facet>
<h:commandButton action="#{testBean.edit(elem)}" value="edit"/>
</h:column>
</h:dataTable>
</h:form>
edit.xhtml
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel value="code"/>
<h:inputText value="#{testBean.selection.code}"/>
<h:outputLabel value="description"/>
<h:inputText value="#{testBean.selection.description}"/>
</h:panelGrid>
<h:commandButton action="#{testBean.update}" value="update"/>
</h:form>
and this bean:
#ManagedBean
public class TestBean implements Serializable
{
private static final long serialVersionUID = 1L;
#EJB
private PersistenceService service;
private Object selection;
private List<UnitType> model;
#PostConstruct
public void init()
{
model = service.findAll(UnitType.class);
}
public String edit(Object object)
{
System.out.println(Tracer.current(object));
setSelection(object);
return "edit";
}
public String update()
{
System.out.println(Tracer.current(selection));
return "list";
}
// getters and setters
}
so the table is rendered, when i click one of the "edit" buttons it navigates to "edit.jsf" showing filled input,
but when i click the "update" buttons it gives me this error:
javax.el.PropertyNotFoundException: /test2/edit.xhtml #27,54 value="#{testBean.selection.code}": Target Unreachable, 'null' returned null
note that i know how to implement a #ViewScoped interface to manage CRUD operations, but this is a simple proof of concept that i need to better understand JSF lifecycle.
so i want "testBean" to be #RequestScoped
UPDATE trying with f:viewParam, still not understanding...
list.xhtml
<?xml version="1.0" encoding="ISO-8859-1"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>test list</title>
</h:head>
<h:body>
<h:messages/>
<h:form id="form">
<h:dataTable value="#{testBean2.model}" rows="10" var="elem">
<h:column>
<f:facet name="header">converterString</f:facet>
#{elem.converterString}
</h:column>
<h:column>
<f:facet name="header">first name</f:facet>
#{elem.firstName}
</h:column>
<h:column>
<f:facet name="header">last name</f:facet>
#{elem.lastName}
</h:column>
<h:column>
<f:facet name="header">action</f:facet>
<h:commandButton action="#{testBean2.edit}" value="edit">
<f:param name="entity" value="#{elem.converterString}"/>
</h:commandButton>
<h:commandButton action="#{testBean2.edit2}" value="edit2">
<f:param name="entity" value="#{elem.converterString}"/>
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
edit.xhtml
<?xml version="1.0" encoding="ISO-8859-1"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">
<f:metadata>
<f:viewParam id="entityParam" name="entity" value="#{testBean2.selection}" converter="entityConverter" required="true"/>
</f:metadata>
<h:head>
<title>test edit</title>
</h:head>
<h:body>
<h:messages/>
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel value="selection"/>
<h:outputText value="#{testBean2.selection.converterString}"/>
<h:outputLabel value="firstName"/>
<h:inputText value="#{testBean2.selection.firstName}"/>
<h:outputLabel value="lastName"/>
<h:inputText value="#{testBean2.selection.lastName}"/>
</h:panelGrid>
<h:commandButton action="#{testBean2.update}" value="update" ajax="false">
<f:param name="entity" value="#{testBean2.selection.converterString}"/>
</h:commandButton>
</h:form>
</h:body>
</html>
testBean2.java
#ManagedBean
public class TestBean2 implements Serializable
{
private static final long serialVersionUID = 1L;
#EJB
private PersistenceService service;
private Object selection;
private List<Person> model;
#PostConstruct
public void init()
{
Tracer.out();
model = service.queryAll(Person.class);
}
public String edit()
{
JsfUtils.addSuccessMessage("edited");
return "edit";
}
public String edit2()
{
JsfUtils.addSuccessMessage("edited");
return "edit?faces-redirect=true&includeViewParams=true";
}
public void update()
{
Tracer.out(selection);
JsfUtils.addSuccessMessage("updated");
}
// getters and setters
}
if i press "edit" button it goes to edit page, but selection is null and no message is showed.
if i press "edit2" button it goes to edit page, but selection is null, showing required message and the url is edit.jsf?entity=
what am i doing wrong?
As my understand, when your second request come to testBean, selection Object is null. If you run this with session bean you may not get this error.
The way I see it, there's no clean way to achieve what you want.
I'll suggest you simply pass around an Id attr between requests as a simple request parameter. So in your post constructor, check if the parameter value is set and based on that, perform a look in your persistence layer.
Alternatively, using the setup you already have, bind the:
<h:inputText value="#{testBean.selection.code}"/>
component to your backing bean and call getValue() on it when necessary. Either way, still untidy.
If you find any other way, please let us know.
Finally I found a way: data will be in a long scope, bean in short.
Note that this is just a proof of concept, not a real use case. And be aware, when dealing with #RequestScope beans, of PrimeFaces lazy DataTable model scope
#ManagedBean
public class TestBean
{
#EJB
private PersistenceService service;
#ManagedProperty("#{viewScope.item}")
private Item item;
#ManagedProperty("#{sessionScope.model}")
private EntityDataModel<Item> model;
#PostConstruct
public void init()
{
if(model == null)
{
model = new EntityDataModel<Item>(Item.class);
Faces.setSessionAttribute("model", model);
}
}
public String update()
{
Faces.getFlash().setKeepMessages(true);
try
{
item = service.update(item);
Faces.setViewAttribute("item", item);
JsfUtils.addSuccessMessage("updated");
return "view?faces-redirect=true&includeViewParams=true";
}
catch(Exception e)
{
e.printStackTrace();
JsfUtils.addErrorMessage(e);
}
return null;
}
// getters and setters, other actions, ...
}
list.xhtml
<p:dataTable value="#{testBean.model}" var="elem" ...>
...
<p:column exportable="false" toggleable="false" headerText="#{bundle.actions}">
<!-- two techniques available for navigation -->
<p:button outcome="view?id=#{elem.converterString}" icon="#{icons.view}" />
<p:commandButton rendered="#{user.isEditAllowed(elem)}"
action="edit?faces-redirect=true&includeViewParams=true" process="#form"
icon="#{icons.edit}">
<f:param name="id" value="#{elem.converterString}" />
</p:commandButton>
</p:column>
</p:dataTable>
view.xhtml
<f:metadata>
<o:viewParam id="itemId" name="id" value="#{viewScope.item}" required="true"
converter="entityConverter" />
</f:metadata>
<ui:composition template="/WEB-INF/templates/template.xhtml">
<ui:define name="content">
<p:panelGrid columns="2">
<h:outputLabel value="#{bundle.name}" />
<h:outputText value="#{item.name}" />
...
</p:panelGrid>
<p:button outcome="list" value="#{bundle.list}" icon="#{icons.list}" />
<p:button rendered="#{user.isEditAllowed(item)}"
outcome="edit?id=#{item.converterString}" value="#{bundle.edit}"
icon="#{icons.edit}" />
</ui:define>
</ui:composition>
edit.xhtml
<f:metadata>
<o:viewParam id="itemId" name="id" value="#{viewScope.item}" required="true"
converter="entityConverter" />
</f:metadata>
<ui:composition template="/WEB-INF/templates/template.xhtml">
<ui:define name="content">
<p:panelGrid columns="2">
<h:outputLabel value="#{bundle.name}" />
<h:panelGroup>
<p:inputText id="name" value="#{item.name}" />
<p:message for="name" />
</h:panelGroup>
...
</p:panelGrid>
<p:commandButton process="#form" update="#form" action="#{testBean.update}"
value="#{bundle.update}" icon="#{icons.update}" />
<p:button outcome="view?id=#{item.converterString}" value="#{bundle.cancel}"
icon="#{icons.cancel}" />
</ui:define>
</ui:composition>
I work with Mojarra 2.1.3.
When the user click on button "refresh don't work", it refresh the content of the ui:repeat.I expect the checkbox to be checked, just as at the initialization.
What I've found: If I remove h:head in the facelet "refresh don't work" works... Any idea ?
The facelet:
<h:head></h:head>
<h:body>
<h:form id="myForm" >
<h:panelGroup id="panelToRefreshOutsideRepeat">
<ui:repeat value="#{sandbox.columns}" var="column">
<h:panelGroup id="panelToRefreshInsideRepeat">
<h2>composite onlyCheckbox:</h2>
<trc:onlyCheckbox value="#{column.value}" />
<br />
<h2>composite onlyInputText:</h2>
<trc:onlyInputText value="#{column.value}" />
<br />
<br/>
<h:commandButton value="Refresh don't work" >
<f:ajax render="panelToRefreshInsideRepeat" />
</h:commandButton>
<h:commandButton value="Refresh work" >
<f:ajax render=":myForm:panelToRefreshOutsideRepeat" />
</h:commandButton>
</h:panelGroup>
<br/>
</ui:repeat>
</h:panelGroup>
The composite for onlyCheckbox and onlyInputText:
<composite:interface>
<composite:attribute name="value"
type="boolean"/>
</composite:interface>
<composite:implementation>
boolean: <h:selectBooleanCheckbox value="#{cc.attrs.value}" />
<!-- for onlyInputText h:inputText instead of h:selectBooleanCheckbox -->
boolean value: #{cc.attrs.value}
</composite:implementation>
and the backing bean:
#ManagedBean
#RequestScoped
public class Sandbox {
public List<Column> columns = Arrays.asList(new Column(true));
public List<Column> getColumns() {
return columns;
}
public void setColumns(List<Column> columns) {
this.columns = columns;
}
public class Column {
private boolean value;
public Column(boolean value) {
this.value = value;
}
public void setValue(boolean value) {
this.value = value;
}
public boolean getValue() {
return this.value;
}
}
}
I can reproduce your problem even on latest Mojarra 2.1.4. It works fine if the checkbox is not inside a composite. This is a bug in Mojarra's <ui:repeat>. It is totally broken in Mojarra. It works perfectly fine on MyFaces 2.1.3.
You have 2 options:
Replace Mojarra by MyFaces.
Use an UIData component instead of <ui:repeat>, e.g. <h:dataTable>, <t:dataList>, <p:dataList>, etc.