JSF actual value input text - jsf

How can I pass the actual value in the text boxt of emailEdit (after changed) to a function or how can I bind this value to another property of a bean when changed ?
Currently I got this :
<h:inputText id="emailEdit"
value="#{portalUserHome.instance.customer.email}">
</h:inputText>
<s:link value="Send mail"
action="#{customerEdit.sendEmail}" rerender="myCustomerEditData,myCustomerData"></s:link>
Thanks in advance

[Assuming you're talking about an EL function, not a JS function here]There are a few ways, but they'll mostly start with you having to bind the text to the page scope:
<h:inputText id="emailEdit" binding="#{emailEdit}" value="#{portalUserHome.instance.customer.email}"/>
From that point, you can pretty much do whatever you want, referring to the textbox using the binding of emailEdit
You could pass the value directly to the method you're interested in (available only starting from EL 2.2)
<s:link value="Send mail" action="#{customerEdit.sendEmail(emailEdit.value)}" rerender="myCustomerEditData,myCustomerData"/>
You could pass the value using the f:attribute tag, and then retrieve the passed attribute in your function
<s:link id="emailLink" value="Send mail"action="#{customerEdit.sendEmail}" rerender="myCustomerEditData,myCustomerData">
<f:attribute name="emailValue" value="#{emailEdit.value}"/>
</s:link>
Retrieving in your function:
public void sendEmail(){
FacesContext ctxt = FacesContext.getCurrentInstance();
UIComponent comp = ctxt.getViewRoot().findComponent("emailLink"); //assuming you already have a FacesContext
String theValue = comp.getAttributes().get("emailValue").toString(); //obligatory null check omitted for brevity
}

Related

JSF PrimeFaces rendering components

Let's say I have a simple method that, like this:
public String test()
{
return "hello";
}
Now let's say I have the following PrimeFace component:
<p:fieldset styleClass="containers" rendered="#{controller.test()}">
<h2>Testing</h2>
<p:outputLabel for="test" value="Test" />
<p:inputText id="test" />
</p:fieldset>
The method above returns "hello". I would like to dynamically show and hide that fieldSet by comparing the returned value of that method to a field of one of my beans. For instance, on the rendered parameter, I would like to do something like: controller.test() != "some variable" which would return true or false. Am I allow to do that? If not, what is the way of doing it?
Basically the goal is to dynamically show and hide some container by comparing the returned value of a method with a bean property.
Look Like you misunderstood rendered
The rendered Attribute
A component tag uses a Boolean EL expression, along with the rendered
attribute, to determine whether or not the component will be rendered.
If you will check above definition you will know what exactly is the use of this attribute.
More you can see below
The rendered attribute which uses Boolean EL expression indicates
whether a component is currently visible or not. The property is
useful when you want to hide components for specific users or based on
condition. The default value of rendered attribute is true.
<h:outputText value=”mapping” rendered=”Boolean EL expression” />
For example, the commandLink component in the following section of a page is not rendered if the cart contains no items:
<h:commandLink id="check"
...
rendered="#{cart.numberOfItems > 0}">
<h:outputText
value="#{bundle.CartCheck}"/>
</h:commandLink>
With your concrete problem you can do like this
Make a String variable call value
Now create get/set methods for above variable
Now in your test method you can add
public void test(){
value="hello";
}
Bur remember you have call test() method of page load
Now in your Xhtml or Jsf or Jsp page
rendered="#{controller.value != 'hello'}"
Or better way create a Boolean variable and do all the magic of hide and show the component

Pass current selected row of p:dataTable to JavaScript function in p:ajax oncomplete

How can I pass current selected row to JavaScript function in <p:ajax oncomplete>?
<p:dataTable value="#{bolt.sites}" var="bolt" selection="#{bolt.selectedSite}" ...>
<p:ajax event="rowSelect" oncomplete="alert(#{bolt.selectedSite.name});" />
I have tried all: #{bolt.selectedSite.name}, #{bolt.name}.
EL expressions in oncomplete attribute are not evaluated after invoking the action. They are already evaluated while rendering the JavaScript code containing that ajax calling logic.
Your best bet is adding a listener method which adds the name as a callback parameter via RequestContext#addCallbackParam() which will then be available as a property of the implicit args object inside oncomplete context.
<p:ajax ... listener="#{bean.select}" oncomplete="alert(args.name)" />
public void select() {
String name = selectedSite.getName();
RequestContext.getCurrentInstance().addCallbackParam("name", name);
}
Unrelated to the concrete problem, you have a syntax error in your initial JavaScript attempt. The property name "name" suggests that it's a string. In JavaScript, all string values should be quoted. So your fictive solution would be oncomplete="alert('#{bolt.selectedSite.name}');"

How can I get my input type hidden value in my faces message bean (when h:commandLink clicked)?

Fairly new to JSF here, so any help much appreciated. I am using JSF 1.2 with WebSphere Portal.
I have an field in my JSP and I am trying to get the value in my FMB. Problem is, when I write the value to the log from my FMB, it is coming out as NULL. Not sure why.
The JSF action is called from a commandLink:
<h:commandLink action="#{planDocBean.classAction}">
The FMB code is as follows:
String state = (String)FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("stateValue");
log.debug("stateValue FMB: " + state);
My JSP:
<input type="hidden" id="stateValue" value="${stateValue}" />
The javascript piece is called from an onChange function for a State value drop down to update the hidden input value. This piece works.
Javascript in JSP:
function setStateValue() {
var stateValue = document.getElementById("stateValue").value;
var e = document.getElementById("states");
var selectedState = e.options[e.selectedIndex].value;
document.getElementById("stateValue").value = selectedState;
}
I know there is the alternative h:inputHidden way of doing it, but I would like to know why this isn't working.
I have also tried this in my FMB, but still NULL:
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
log.debug("stateValue 1: " + req.getParameter("stateValue"));
Again, I would be very grateful for any assistance.
Thanks!

Using JSF Validator

I am using Prime faces 3.4.1 as component framework and JSF 2.0 as the server side framework
Following is my requirement
1) I have a field with label as "Meeting Required". Then I have SelectOneRadio with two options "No" and "Yes" with default value as "No". I am using JSF/HTML component h:SelectOneRadio.
2) I have another field which is Calendar component and this is a primefaces calendar component. When the user selects "Yes" which indicates the "Meeting is required" and the user should select a date from the calendar control.
3) If the user selects "Yes" and does not select a date, then a Validation message should be displayed indicating that the date should be selected.
I created a Custom Validation component and attached to the SelectOneRadio and I am able to see the selected value in the Custom validator. Now, I try to get the value from the Calendar component to check if the value is empty, through UIComponent.getParent().findCompoent("rvmDate"), I get the component but I do not know how to check if the date component is empty or contain any values.
Please help me out to get the date value selected by the user.
Please help me out to resolve the issue. Or is there any other way? Please find the source code.
XHTML Page
<h:selectOneRadio id="rvmMeetingOption"
readonly="#{wipMB.rvmMeetingOptionReadOnly}"
value="#{wipMB.requirementsMeeting}"
disabled="#{wipMB.rvmMeetingOptionDisabled}"
validator="#{wipMB.validateRVMDate}"
validatorMessage="Please enter RVM Date>
<f:selectItem itemLabel="No" itemValue="0"></f:selectItem>
<f:selectItem itemLabel="Yes" itemValue="1" ></f:selectItem>
<f:attribute value="#{rvmDateComp}" name="rvmDateComp"></f:attribute>
</h:selectOneRadio>
<p:calendar id="rvmDate"
readonly="#{wipMB.rvmMeetingDateReadOnly}"
disabled="#{wipMB.rvmMeetingDateDisabled}"
readonlyInput="true"
navigator="true" mode="popup"
pattern="dd/MM/yyyy"
value="#{wipMB.rvmDate}"
effect="explode"
yearRange="1900:2500"
style="margin-left:5px"
binding="#{rvmDateComp}"
</p:calendar>
<p:message id="rvmDateMsg" for="rvmDate" display="both" ></p:message>
Custom Validator
public void validateRVMDate(FacesContext context, UIComponent component, Object value)
throws ValidatorException
{
String invalidDate;
String rvmOption;
Date rvmDate;
String rvmDt = "";
try
{
FacesContext fc = FacesContext.getCurrentInstance();
rvmOption = value.toString();
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
UIInput rvmCompDt = (UIInput)component.getAttributes().get("rvmDateComp");
rvmDateId = rvmCompDt.getId();
rvmDt = rvmCompDt.getSubmittedValue() == null ? "" : rvmCompDt.getSubmittedValue().toString();
if (rvmOption.equals("1") && rvmDt.isEmpty())
{
FacesMessage msg = new FacesMessage("RVM date is required");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
fc.addMessage("rvmDateMsg", msg);
throw new ValidatorException(msg);
}
}
catch (Exception ex)
{
String msg = ex.getMessage();
}
}
In JSF each component is a little MVC stack of its own; there is the Model (stored as value), the Controller (the component object) and View (renderer). Validators and controllers are part of the architecture and are needed to move the values between the model and the view.
While JSF Validators play an important role, it is important only INSIDE this little MVC stack. They were not designed to "validate forms", they are made strictly to "validate component value". Lamentably, the name "validator" makes everyone who comes to JSF think, that each time any validating needs to be done, validator is the solution. Strangely, converters are not so abused.
In your case, building a custom validator created a strange situation, where:
validator and view have a cyclic dependency on each other,
there is a need to use hacks (such as "immediate") and low-level APIs,
hard-coding view logic in an unlikely place,
requires much more knowledge and is flaky. For example the logic of acquiring value from calendar might be different depending on whether radio button is before or after calendar in document order.
The problems above could be solved, but since they all arise from abusing JSF architecture, I think it would be better to rethink the problem. Since your validation concerns flow of application, it is a perfect fit for the action method, where all the complications will dissolve into a single, simple "if" statement with a conditional "addMessage".
You first need to remove immediate="true" from the <p:calendar>, otherwise it's not processed at all when the radio button is processed.
Then, to check if a string is null or empty, just do
String dt = (String) uiCalendar.getSubmittedValue();
if (dt == null || dt.isEmpty()) {
// dt is null or empty. Throw validator exception depending on the
// current radio button value. Note: you should not catch it yourself!
}
Note that this has nothing to do with JSF. It's just basic Java. Your initial attempt as if (dt == "") is indeed completely invalid. The String is an object, not a primitive. The == compares objects by reference, not by their internal value. Technically, you should have used if (dt.equals("")) instead, but the isEmpty() is nicer.
Unrelated to the concrete problem, a much easier way is to just check the radio button value in the required attribute of the calendar component. First bind the radio button component via binding to a variable in the view, then reference its UIInput#getValue() method in the required attribute.
<h:selectOneRadio id="rvmMeetingOption" binding="#{rvmMeetingOption}"
readonly="#{wipMB.rvmMeetingOptionReadOnly}"
value="#{wipMB.requirementsMeeting}"
disabled="#{wipMB.rvmMeetingOptionDisabled}">
<f:selectItem itemLabel="No" itemValue="0"></f:selectItem>
<f:selectItem itemLabel="Yes" itemValue="1" ></f:selectItem>
</h:selectOneRadio>
<p:calendar id="rvmDate"
readonly="#{wipMB.rvmMeetingDateReadOnly}"
disabled="#{wipMB.rvmMeetingDateDisabled}"
readonlyInput="true"
navigator="true" mode="popup"
pattern="dd/MM/yyyy"
value="#{wipMB.rvmDate}"
effect="explode"
yearRange="1900:2500"
style="margin-left:5px"
required="#{rvmMeetingOption.value == 1}">
</p:calendar>
use
UIInput uiCalendar = (UIInput) component.getParent().findComponent("rvmDate");
Date test = uiCalendar.getValue();
if(test==null){
throw ValidatorException
}
test will then have the date filled in or will be null when nothing is chosen in teh date field

Sending values with <h:commandbutton> not working working properly in jsf

When i tried to send some values with h:commandButton... i recieved null value in the bean...
my xhtml code is:
<p:commandButton action="#{favouriteAction.setFavourite}" value="Add as Favorite" rendered="#{favouriteBean.favouriteButton}">
<f:setPropertyActionListener target="#{favouriteAction.ngoID}" value="#{InsertDataDaoService.ngo_id}"></f:setPropertyActionListener>
</p:commandButton>
In the backing bean i just tried to print the value which i passed with my command button,but it becomes null...
In favouriteAction.java(My backing Bean)
public Integer ngoID;
public Integer getNgoID() {
return ngoID;
}
public void setNgoID(Integer ngoID) {
this.ngoID = ngoID;
}
public String setFavourite(){
System.out.println("Ngo id: "+ngoID);
System.out.println("Ngo id: "+getNgoID);
return "";
}
In console i dint get any exceptions, my o/p is
Ngo id: 0
Ngo id: 0
that is null, and it doesnt get passed..
The <f:setPropertyActionListener> is evaluated during the request of the form submit, not during the request of displaying the form. So if its value #{InsertDataDaoService.ngo_id} is not preserved for that request, then it will fail.
You have basically 2 options:
Ensure that #{InsertDataDaoService.ngo_id} is preserved for the request of the form submit. How exactly do to that depends on the functional requirements which are not clear from the question. But generally, putting the #{InsertDataDaoService} bean in the view scope by #ViewScoped and making sure that you aren't doing any business job in the getter method should be sufficient.
Replace <f:setPropertyActionListener> by <f:param> with #ManagedProperty.
<p:commandButton action="#{favouriteAction.setFavourite}" value="Add as Favorite" rendered="#{favouriteBean.favouriteButton}">
<f:param name="ngoID" value="#{InsertDataDaoService.ngo_id}" />
</p:commandButton>
with
#ManagedProperty("#{param.ngoID}")
private Integer ngoID;
This way the value will be retrieved (and inlined as part of a JavaScript helper function of the commandButton) during the request of displaying the form, not evaluated during the request of submitting the form.
See also:
How can I pass selected row to commandLink inside dataTable?
Have you checked that the value of InsertDataDaoService.ngo_id is not NULL?
Try to replace it with a constant value. Does it work?

Resources