I wanted to write a code to get the input value of prime faces calendar input value.
<div style="padding-left: 300px;">
<p:calendar value="#{calendarBean.fromDate}" id="fromButton" showOn="button" pattern="dd-MMMM-yyyy"
required="true" requiredMessage="Insert From Date!">
</p:calendar>
<p:calendar value="#{calendarBean.toDate}" id="toButton" showOn="button" pattern="dd-MMMM-yyyy"
style="padding-left: 100px;padding-right: 30px" required="true" requiredMessage="Insert To Date!">
</p:calendar>
<p:commandButton actionListener="#{userLeaveBean.addAppliedLeave}" styleClass="apply_button" value="Create Leave">
<f:attribute name="userId" value="#{employee.name}"/>
</p:commandButton>
</div>
I want to pass three parameter values(userId,fromDate,toDate) through the method call
<p:commandButton actionListener="#{userLeaveBean.addAppliedLeave}" styleClass="apply_button" value="Create Leave">
using method addAppliedLeave().
I am able to send the userId using:
<f:attribute name="userId" value="#{employee.name}"/> but how can I pass the values for calender input at run time?
also I am able to get the value of userId in method addAppliedLeave()
public void addAppliedLeave(ActionEvent event){
String userId = (String)event.getComponent().getAttributes().get("userId");
System.out.println(userId);
String fromDate = (String)event.getComponent().getAttributes().get("fromDate");
System.out.println(fromDate);
}
but I am totaly helpless about dynamic input of <p:calendar> value.
Please help.
You can easily get p:calender value at run time using p:ajax as shown here
/* view.xhtml */
<p:calendar value="#{yourBackingBean.user.fromDate}" mode="inline" id="inlineCal">
<p:ajax event="dateSelect" listener="#{yourBackingBean.handleDateSelect}" update="growl" />
</p:calendar>
/* Backing bean */
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ManagedBean
#ViewScoped
public class YourBackingBean implements Serializable {
private static final long serialVersionUID = 1L;
private User user;
public void handleDateSelect(DateSelectEvent event) {
System.out.println("dynamic date selected is "+user.getFromDate());
// so here you will get everytime your changed date.
//As this method will get called everytime whenever you will change your date from p:calender component.
}
public User getUser() {
if(user==null){
user=new User();
}
return user;
}
}
/* javaBean */
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Date fromDate;
private Date toDate;
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
}
Related
I'm using PrimeFace4.0, JSF 2.2, Java, and XHTML. I have a string value that I need to pass from one bean to another. The value is selected on one XHTML page and when the user clicks to select, a new web page is launched. I can see from my server output that the value is successfully collected by the first bean (TestSelectBean), but I can't seem to get it into the next bean (TargetBeanFranz). When a String is hard coded into the bean, it works correctly. However, when I try to use the managed property to call it as per the user input, I get a NullPointer at the line of code (85) where I'm trying to use it.
The first HTML: testselect.xhtml
//irrelevant code
<p:layoutUnit position="center">
<h:form>
<p:selectOneRadio id="Test" value="#{testSelectBean.selectedNameOfExperiments}" >
<f:selectItems id="selectedNameOfExperiments" value="#{testSelectBean.nameofexperiments}" var="entry" itemValue="#{entry.key}" itemLabel="#{entry.value}" />
</p:selectOneRadio>
<p:commandLink id="nonAjax" action="open" actionListener="#{testSelectBean.getParameters}" style="margin-right:20px;" ajax="false">
<h:outputText value="Submit" />
</p:commandLink>
</h:form>
</p:layoutUnit>
The user chosen selectedNameOfExperiments is succsefully passed to TestSelectBean:
#ManagedBean(name = "testSelectBean", eager = true)
#SessionScoped
public class TestSelectBean implements Serializable {
private static final long serialVersionUID = 1L;
protected String selectedNameOfExperiments;
private final Map<String, String> nameofexperiments;
private transient String selected;
public TestSelectBean() throws SQLException {
selected = new String();
nameofexperiments = new HashMap<String, String>();
XYexpdataServiceAdapter xydata = new XYexpdataServiceAdapterImpl();
List<String> dbnameofexperiments = xydata.getNameofexperiments();
for (String ta : dbnameofexperiments) {
nameofexperiments.put(ta, ta);
}
}
public String getSelectedNameOfExperiments() {
return selectedNameOfExperiments;
}
public void setSelectedNameOfExperiments(String selectedNameOfExperiments1) {
this.selectedNameOfExperiments = selectedNameOfExperiments1;
}
public Map<String, String> getNameofexperiments() {
return nameofexperiments;
}
public void getParameters() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You've selected Experiment:" + selectedNameOfExperiments));
System.out.println("You've selected Experiment:" + selectedNameOfExperiments);
}
}
However, the XHTML FranzwPopup will not launch unless Experiment is hard coded into TargetBeanFranz.
//irrelevant code
<p:layoutUnit position="center">
<p:panelGrid columns="2" style=" font-size: 14">
<h:outputLabel value="Description" style="font-size: 20"/>
<h:outputText value="Neutron-induced production of protons, deuterons and tritons in Copper and Bismuth."/>
<h:outputLabel value="Reference" style="font-size: 20"/>
<h:outputText value="Nuclear Physics A510 (1990) 774-802 (Franz, et. al.)"/>
</p:panelGrid>
<form action="http://localhost:8080/primefaces/faces/handle.xhtml" method="get" name="login" onsubmit="process();
return false;" style="overflow-y: scroll">
Click to display chart data in a table.<br />
<input type="submit" value="Display"/>
</form>
<h:form>
<h:panelGrid columns="4" cellpadding="5">
<p:selectCheckboxMenu id="menu1" value="#{targetBeantFranz.selectedTargets}" label="Targets" filter="true" filterMatchMode="startsWith"
panelStyle="width:220px">
<f:selectItems value="#{targetBeantFranz.targets}" />
</p:selectCheckboxMenu>
<p:selectCheckboxMenu id="menu2" value="#{targetBeantFranz.selectedSecondaries}" label="Secondaries" filter="true" filterMatchMode="startsWith"
panelStyle="width:220px">
<f:selectItems value="#{targetBeantFranz.secondaries}" />
</p:selectCheckboxMenu>
<p:selectCheckboxMenu id="menu3" value="#{targetBeantFranz.selectedReactions}" label="Reactions" filter="true" filterMatchMode="startsWith"
panelStyle="width:220px">
<f:selectItems value="#{targetBeantFranz.reactions}" />
</p:selectCheckboxMenu>
<p:selectCheckboxMenu id="menu4" value="#{targetBeantFranz.selectedBeamEnergies}" label="Beam Energy" filter="true" filterMatchMode="startsWith"
panelStyle="width:220px">
<f:selectItems value="#{targetBeantFranz.beamenergies}" />
</p:selectCheckboxMenu>
</h:panelGrid>
<p:panel header="Resulting Plots">
<p:commandLink id="nonAjax" actionListener="#{targetBeantFranz.getParameters}" style="margin-right:20px;" ajax="false">
<button id="change">Submit Query</button>
</p:commandLink>
<div id="container" style="min-width: 310px; margin: 0 auto"></div>
</p:panel>
</h:form>
</p:layoutUnit>
//more irrelevant
Instead, I get a NPE on line 85 of TargetBeanFranz where I try to initialize Experiment.
//stuff
#ManagedBean(name = "targetBeantFranz", eager = true)
#SessionScoped
public class TargetBeanFranz implements Serializable {
#ManagedProperty(value="#{testSelectBean}")
private TestSelectBean testSelectBean;
public TestSelectBean getTestSelectBean(){
return testSelectBean;
}
public void setTestSelectBean (TestSelectBean testSelectBean) {
this.testSelectBean = testSelectBean;
}
private static final long serialVersionUID = 1L;
private String Experiment;
//more stuff
public TargetBeanFranz() throws SQLException {
targets = new HashMap<String, String>();
selectedTargets = new ArrayList<String>();
secondaries = new HashMap<String, String>();
selectedSecondaries = new ArrayList<String>();
reactions = new HashMap<String, String>();
selectedReactions = new ArrayList<String>();
beamenergies = new HashMap<String, String>();
selectedBeamEnergies = new ArrayList<String>();
seriesDataArray = new ArrayList<String>();
seriesDataArArray = new ArrayList<ArrayList<String>>();
seriesNameArray = new ArrayList<String>();
seriesToolTipArray = new ArrayList<String>();
seriesErrorArray = new ArrayList<String>();
seriesErrorArArray = new ArrayList<ArrayList<String>>();
allselected = new ArrayList<XYexpdata>();
Experiment = testSelectBean.getSelectedNameOfExperiments(); //This is line 85 and where I'm getting the NPE.
XYexpdataServiceAdapter xydata = new XYexpdataServiceAdapterImpl();
List<String> dbtargets = xydata.getTargetNamesbyExperiment(Experiment);
for (String ta : dbtargets) {
targets.put(ta, ta);
}
List<String> dbsecondaries = xydata.getSecondaryNamesbyExperiment(Experiment);
for (String ta : dbsecondaries) {
secondaries.put(ta, ta);
}
List<String> dbreactions = xydata.getReactionNamesbyExperiment(Experiment);
for (String ta : dbreactions) {
reactions.put(ta, ta);
}
List<String> dbbeamenergies = xydata.getBeamEnergybyExperiment(Experiment);
for (String ta : dbbeamenergies) {
beamenergies.put(ta, ta);
}
}
//more code
I think the reason for your problem is, that the signature of the action listener in your command link does not match.
The method in the bean has to be of the following type:
public void getParameters(javax.faces.ActionEvent event) {
.....
}
If you are using Java EE 7 you should also avoid the annotations in the package javax.faces.bean, since they are abandoned. Use CDI beans, it makes life easier:
#Named
#SessionScoped
public class TestSelectBean {
...
}
#Named
#SessionScoped
public class TargetBeanFranz {
#Inject
private TestSelectBean testSelectBean;
....
}
See more about the CDI topic here: Backing beans (#ManagedBean) or CDI Beans (#Named)?
My h:form contains a p:selectOneMenu component, which has two values single and multiple. The h:form also contains a default p:inputText. My objective is to add multiple p:inputText component only when value multiple is selected. Please see the attached screenshot-
Below is my view, which suppose to send ajax request, whenever icon button is clicked-
<h:form>
<p:panel header="Dynamically Add textbox">
<p:selectOneMenu id="runType" value="#{repeateRun.runType}">
<f:selectItems value="#{repeateRun.runList}" var="runType" itemLabel="#{runType}" itemValue="#{runType}" />
<p:ajax update="outPanel" listener="#{repeateRun.renderComponent}" />
</p:selectOneMenu>
<h:panelGrid id="runList">
<ui:repeat value="#{repeateRun.runs}" var="run">
<p:inputText value="#{run.runValue}" />
</ui:repeat>
</h:panelGrid>
<p:outputPanel id="outPanel">
<p:commandButton update="runList" icon="ui-icon-plusthick" title="Add more" rendered="#{repeateRun.showAddButton}">
<f:ajax render="runList" listener="#{repeateRun.addRun}" />
</p:commandButton>
</p:outputPanel>
</p:panel>
</h:form>
The #ViewScoped #ManagedBean RepeateRun is following-
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 javax.faces.event.ActionEvent;
#ManagedBean
#ViewScoped
public class RepeateRun implements Serializable {
private static final long serialVersionUID = 1L;
private List<String> runList;
private List<Run> runs;
private int runValue;
private String runType;
private boolean showAddButton = false;
private static final String SINGLE = "Single";
private static final String MULTIPLE = "Multiple";
//Note : Getters Setters are removed while putting here
#PostConstruct
public void initBean() {
this.setRunList(this.populateRunList());
this.setRuns(this.populateRuns());
}
public void addRun() {
if (this.runs == null) {
this.setRuns(this.populateRuns());
} else {
this.runs.add(this.defaultRun());
}
}
public void renderComponent() {
if (this.getRunType().equals(SINGLE)) {
this.setShowAddButton(false);
} else {
this.setShowAddButton(true);
}
}
private List<String> populateRunList() {
List<String> runList = new ArrayList<String>();
runList.add(SINGLE);
runList.add(MULTIPLE);
return runList;
}
private Run defaultRun() {
Run defaultRun = new Run();
defaultRun.setRunValue(1);
return defaultRun;
}
private List<Run> populateRuns() {
List<Run> runs = new ArrayList<Run>();
runs.add(this.defaultRun());
return runs;
}
}
So after selecting the value Multiple in f:selectItems the plus icon button comes but the button is not invoking attached method i.e. addRun. To confirm the method addRun call after clicking, I put some sysout statements in addRun method. I saw that sysout is not flushed. At the same time I saw some xml response in the firebug.
Where is the problem?
The problem was with f:ajax which doesn't work with p:commandButton. Below are the culprit lines-
<p:commandButton update="runList" icon="ui-icon-plusthick" title="Add more" rendered="#{repeateRun.showAddButton}">
<f:ajax render="runList" listener="#{repeateRun.addRun}" />
</p:commandButton>
The above lines should be replaced with below line
<p:commandButton actionListener="#{repeateRun.addRun}" update="runList" icon="ui-icon-plusthick" title="Add more" rendered="#{repeateRun.showAddButton}" />
I read many similar questions, but I cannot figure out how to solve my problem:
I wrote a composite component backed by a view-scoped, self-contained managed bean.
The component consists of an autocomplete textbox with a button that opens a dialog. The user can select an item either by name (autocomplete) or selecting a node in a tree (dialog).
The backing bean implements all the stuff needed (data access, tree-logics etc) and should expose the selected item (as a POJO).
Now I have 2 problems:
Due to the complexity of the tree management, selectedObj property is accessed by a getter and a setter that do some stuff in the bean: they are not simply accessing a class field. Now I'm passing the entire bean as an attribute. How can I just make the bean's selectedObj the "value" attribute of my composite component?
How can I use multiple instance of my component in the same view?
Here is an example of the component:
<cc:interface>
<cc:attribute name="bean" type="com.yankee.OUTreeBean" required="true"/>
<cc:attribute name="listener" method-signature="void listener()"/>
</cc:interface>
<cc:implementation>
<p:dialog id="#{cc.id}_dialog" widgetVar="_dlg" header="Select OU" modal="true" dynamic="true" >
<p:toolbar>
<!-- some buttons to refresh, expand, collapse etc. -->
</p:toolbar>
<p:tree id="#{cc.id}_tree" value="#{cc.attrs.bean.root}" var="node"
selectionMode="single"
selection="#{cc.attrs.bean.selectedNode}">
<p:ajax event="select" update="#form" listener="#{cc.attrs.listener}" oncomplete="if (!args.validationFailed) _dlg.hide()" />
<p:treeNode>
<h:outputText value="#{node.OU_NAME}" />
</p:treeNode>
</p:tree>
</p:dialog>
<p:autoComplete id="#{cc.id}_inner" value="#{cc.attrs.bean.selectedObj}" completeMethod="#{cc.attrs.bean.completeObj}"
var="obj" itemLabel="#{obj.OU_NAME}" itemValue="#{obj}"
forceSelection="true"
converter="ouConverter"
multiple="false"
minQueryLength="2">
<p:ajax event="itemSelect" listener="#{cc.attrs.listener}" update="#form"/>
</p:autoComplete>
<div style="float: right">
<p:commandButton id="bSearch" icon="ui-icon-search" onclick="_dlg.show()"/>
</div>
</cc:implementation>
The backing bean of the COMPONENT:
#ManagedBean
#ViewScoped
public class OUTreeBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<OU> data; // Data as plain list
protected TreeNode root; // root node of data as a tree
protected TreeNode selectedNode;
#PostConstruct
private void init() throws SQLException {
refreshData();
}
public OU getSelectedObj() {
if (selectedNode == null) {
return null;
}
return ((OU) selectedNode.getData());
}
public void setSelectedObj(OU ou) {
// Find the right tree node and do whatever needed
}
public TreeNode selectedNode getSelectedNode() {
// Blah blah
}
public void setSelectedNode(TreeNode selectedNode) {
// Blah blah
}
public List<OU> completeObj(String namePattern) {
// Autocomplete handler
}
public void refreshData() {
// Blah blah
}
// etc...
}
The using page excerpt:
<ism:selectOUTree id="cbSelectOu" bean="#{myBean.ouFilterBean}" listener="#{myBean.onOUChange}"/>
The backing bean of the PAGE:
#ManagedBean
#ViewScoped
public class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{oUTreeBean}")
private OUTreeBean ouFilterBean;
public void onOUChange() throws SQLException {
// Blah blah
}
}
I had the same problem few days ago. Just like you I used ManagedBean as an object that should do the job. After some time I figured out that I should just create FacesComponent. I'm new in JSF so it wasn't that easy to find the solution but it solved all my problems. This is how does it work:
view.xhtml
<h:body>
<cc:interface componentType="playerComponent">
<cc:attribute name="playerId" required="true"/>
</cc:interface>
<cc:implementation>
<c:set var="inplaceId" value="inplace-#{cc.attrs.playerId}" />
<c:set var="outputId" value="output-#{cc.attrs.playerId}" />
<h:form id="form-#{cc.attrs.playerId}">
<p:inplace editor="false" widgetVar="#{inplaceId}">
<h:inputText value="#{cc.player.name}" id="outputId"/>
<p:commandButton onclick="#{inplaceId}.save()" action="#{cc.save}" update="#{outputId}" value="save" />
<p:commandButton onclick="#{inplaceId}.cancel()" update="#{outputId}" value="cancel" />
</p:inplace>
</h:form>
</cc:implementation>
</h:body>
PlayerComponent.java
#FacesComponent("playerComponent")
public class PlayerComponent extends UINamingContainer {
private Player player;
private void init() {
Object idObj = getAttributes().get("playerId");
if (idObj != null) {
// create player object
}
}
public void save() {
// save player object
}
public Player getPlayer() {
if (player == null) {
init();
}
return player
}
}
Player.java (entity)
public class Player {
private name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
As I wrote I'm new in JSF and probably player object should be created in different way (using #PostConstruct on in constructor?) but this work.
I have a custom UIInput wrapped in a composite component like this:
<cc:interface componentType="SingleUpload">
<cc:attribute name="value" required="true" />
...
</cc:interface>
<cc:implementation>
...
<p:fileUpload id="fileUpload" update="#form" auto="true"
fileUploadListener="#{cc.fileUploaded}" rendered="#{cc.attrs.value == null}"/>
...
<h:commandButton rendered="#{cc.attrs.value != null}" action="#{cc.removeFile}">
<p:ajax execute="#this" update="#form" />
</h:commandButton>
...
</cc:implementation>
The backing component looks like this:
#FacesComponent(value = "SingleUpload")
public class SingleUpload extends UIInput implements NamingContainer, Serializable {
/** */
private static final long serialVersionUID = 2656683544308862007L;
#Override
public String getFamily() {
return "javax.faces.NamingContainer";
}
public void fileUploaded(FileUploadEvent event) throws IOException {
FileData file = new FileData();
file.setContentMimeType(MimeTypeUtils.getContentType(event.getFile().getContentType(), event.getFile().getFileName()));
file.setInputStream(event.getFile().getInputstream());
file.setName(FilenameUtils.getName(event.getFile().getFileName()));
setValue(file);
}
public void removeFile() {
resetValue();
// value should be null now, but it is not, why??
FileData value=(FileData) getValue();
}
}
It is used this way:
<ki:singleUpload value="#{fileModel.file}" title="File Upload" />
So when the action removeFile is called, i want to set the value to null. This works, when I follow these steps:
load a page containing a singleUpload component with no initial value (fileModel.file == null)
upload a file, so value in SingleUpload is not null anymore
remove the file
But when I do the following
load a page containing a singleUpload component with an initial value (fileModel.file != null)
remove the intial value (click on button, removeFile is called)
=> removing the value from the component does not seem to be possible. Why??
I want to pass in the session scoped the selected radio button value. My code will not work.
Here is the view (searchPerson.xhtml):
<h:form>
<h:selectOneRadio id="searchRadio" value="#{controller.radioButtonFlag}" valueChangeListener="#{controller.selectRadioButton}" >
<f:selectItem itemValue="fachid" itemLabel="#{msg.fachId}">
<f:attribute name="radioButtonField" value="fachid" />
</f:selectItem>
<f:selectItem itemValue="vngw" itemLabel="#{msg.VNGW}">
<f:attribute name="radioButtonField" value="vngw" />
</f:selectItem>
</h:selectOneRadio>
... <h:commandButton action="#{controller.search}" value="#{msg.search}"></h:commandButton>
Here is the managed bean:
#ManagedBean #SessionScoped public class Controller { private String radioButtonField = "fachid"; private boolean VNGWSelected = false; public void selectRadioButton(ValueChangeEvent event){
String select = (String) event.getComponent().getAttributes().get("radioButtonField");
if(select.equals("vngw"))
VNGWSelected = true;
} public String search() {... if(!VNGWSelected){logger.info("FachID RadioButton selected."); else{... logger.info("VNGW RadioButton selected."); ...} return "personsearch"; } ...} ... }
Can someone please tell me what am I doing wrong here?
Thanks in advance.
Try this:
<h:selectOneRadio id="searchRadio" value="#{controller.select}" >
<f:selectItem itemValue="fachid" itemLabel="#{msg.fachId}" />
<f:selectItem itemValue="vngw" itemLabel="#{msg.VNGW}" />
</h:selectOneRadio>
<h:commandButton action="#{controller.search}" value="#{msg.search}"></h:commandButton>
I am not sure of what are the semantics of your bean or what is the goal of the controller but it is better to use an attribute and getters and setters.
#ManagedBean
#SessionScoped
public class Controller {
private String radioButtonField = "fachid";
private boolean VNGWSelected = false;
private String select;
public void setSelect(String select){
this.select = select;
if(select.equals("vngw"))
VNGWSelected = true;
}
public String getSelect(){
return select
}
public String search() {...
if(!VNGWSelected){
logger.info("FachID RadioButton selected.");
else{...
logger.info("VNGW RadioButton selected."); ...}
return "personsearch";
} ...} ... }