JSF richfaces getElementById - jsf

I am using jsf2 and richfaces 4.X how can i get the richfaces enabled input field's current value ? equal to getElementById('field_name').vlue
I tried some of the methods named like findcomponent.value and element.value but they give me old value which was while page was loaded b/c findcomponent and element method returns server side UI.components instead client side components ?

I guess you are to use rich:clientId function to render a correct identifier into your java script.
For example:
var myElement = document.getElementById("#{rich:clientId('field_name')}");
See also RichFaces rich:clientId within facelets

If you check the HTML generated, you could see that every JSF / RF element has his id like :. For example:
<h:form id="frmSample">
<h:inputText id="txtSample" value="#{mybean.someTextValue}" />
</h:form>
The HTML generated will be:
<form method="POST">
<input type="text" id="frmSample:txtSample" />
</form>
So, in JavaScript you could reference the element by this id.
var txtValue = document.getElementById('frmSample:txtSample').value;
Also, for the RF composite HTML components like rich:tab or rich:calendar you could use the component ID generated by HTML but I'll recommend "#{rich:clientId('field_name')}" as #DRCB has explained in his post.

To get the richfaces components values use the rich:component and the getValue() methods.
To get the jsf library components values use the rich:element and the value JS methods.
Example:
<h:form>
<h:inputText id="textField" value="#{bean.value1}" />
<a4j:commandButton value="displayTextField" action="doSomething()"
onclick="alert('v:'+ #{rich:element('textField')}.value); return true;" />
<rich:inplaceInput id="richField" value="#{bean.value1}" />
<a4j:commandButton value="displayRichField" action="doSomething()"
onclick="alert('v:'+ #{rich:component('richField')}.getValue()); return true;" />
</h:form>
They both work even in a rich:dataTable, without adding the id of the datatable or something. Richfaces is quite smart and find the ids of the 'current row'
example:
<h:form>
<rich:dataTable id="mydatatable" value="bean.findValues()" var="myvar">
<rich:column>
<h:inputText id="textField" value="#{myvar.text1}" />
<a4j:commandButton value="displayTextField" action="doSomething()"
onclick="alert('v:'+ #{rich:element('textField')}.value); return true;" />
</rich:column>
<rich:column>
<rich:inplaceInput id="richField" value="#{myvar.text2}" />
<a4j:commandButton value="displayRichField" action="doSomething()"
onclick="alert('v:'+ #{rich:component('richField')}.getValue()); return true;" />
</rich:column>
</rich:dataTable>
</h:form>

Related

InputText not working with when using length() function With Flash object?

When page rendered first time textbox was empty and when i click a button and called a action and update the value like this it worked and textbox updated with new value
Flash flash = FacesContext.getCurrentInstance().getExternalContext()
.getFlash();
flash.put("errorMessage",featuesObj.getName() + "Some Error came");
<h:inputText value="#{flash.errorMessage }" id="mymessage" />
But now made a little changes in textbox and added a rendered now text box not displayed even pressing command button while #{flash.errorMessage} already have some String value
<h:inputText value="#{flash.errorMessage}" rendered="#{flash.errorMessage.length() gt 0 }" id="mymessage" />
Even i tried below code as well
<h:inputText value="#{flash.errorMessage.length()}" id="mymessage" />
Its always showing false in textbox even i press the button.
Can someone please let me know what can be issue?
This is the answer of my problem
Ajax rendering of content which is by itself conditionally rendered
Ajax rendering takes place fully at the client side and expects the to-be-updated HTML element to be already in the JSF-generated HTML output.
Following will not work when #{bean.renderResult} defaults to false:
<h:form id="form">
<h:commandButton value="Submit" action="#{bean.toggleRenderResult}">
<f:ajax render=":result" />
</h:commandButton>
</h:form>
<h:outputText id="result" value="#{bean.result}" rendered="#{bean.renderResult}" />
You need to ensure that the render ID points to a component which is already present in the JSF-generated HTML output.
Following will work:
<h:form id="form">
<h:commandButton value="Submit" action="#{bean.toggleRenderResult}">
<f:ajax render=":result" />
</h:commandButton>
</h:form>
<h:panelGroup id="result">
<h:outputText value="#{bean.result}" rendered="#{bean.renderResult}" />
</h:panelGroup>
http://balusc.blogspot.in/2011/09/communication-in-jsf-20.html#AjaxRenderingOfContentWhichIsByItselfConditionallyRendered

Dynamic navigation with parameter passing in JSF

I want to pass the "title" parameter in the following listing dynamicaly to another jsf Facelet, depending on the selection of the selectOneMenu. My first approach looks like this:
<h:form id="form">
<p:selectOneMenu value="#{exerciseEditorBean.selectedExerciseType}" >
<f:selectItem itemLabel="Multiple Choice Exercise" itemValue="MultipleChoiceExercise" />
<f:selectItem itemLabel="Vocabulary Test" itemValue="VocabularyTest" />
</p:selectOneMenu>
<h:outputText value="Enter Title of your Exercise: " />
<h:inputText id="title" value="#{exerciseEditorBean.exerciseTitle}" />
<h:commandButton value="Next" action="#{exerciseEditorBean.openEditor()}" />
</h:form>
The ExerciseEditorBean is ViewScoped.
The openEditor() function then decides by the selectedExerciseType attribute which Facelet to show next and returns something like "multipleChoiceEditor.xhtml".
How can I now pass the titel attribute to this Facelet?
I now use the f:ViewParam in the target servelet, which works well except, that "multipleChoiceEditor.xhtml?includeViewParams=true" does not work, but this is another issue. Thanks for the discussion!

Scrolling to anchor or page bottom after JSF form validation fail

I have a contact form at the bottom of a page with required and validated form fields. If validation fails, how can I get the scroll position back to the bottom of the page?
I want this page to work with Javascript disabled, so no AJAX solutions. I have something like this:
<a id="contact"></a>
<h:form id="cform">
<h5>Contact!</h5>
<h:outputLabel for="name">Name:
<h:message id="nameMsg" for="name" />
</h:outputLabel>
<h:inputText id="name" value="#{bean.name}" required="true" requiredMessage="Please enter name!" />
<h:outputLabel for="email">Email:
<h:message id="emailMsg" for="email" />
</h:outputLabel>
<h:inputText id="email" value="#{bean.email}" required="true" requiredMessage="Email is required!">
<f:validator validatorId="myValidator" />
</h:inputText>
<h:outputLabel for="comment">Comment:
<h:message id="commentMsg" for="comment" />
</h:outputLabel>
<h:inputTextarea id="comment" value="#{bean.comment}" required="true" requiredMessage="Please enter a comment!"/>
<h:commandButton action="#{bean.go}" id="send" value="send" />
</h:form>
I thought about doing validations on the bean side and doing manual redirects to the appropriate anchor, but that seems to defeat the purpose of using JSF to begin with. I assume there is an easy way to do this, but I'm having trouble Googling a solution because I'm probably not wording the question right. Any one?
You can use <f:event type="postValidate"> to have a listener hook right after the validations phase. You can use FacesContext#isValidationFailed() to check if validation has failed or not. You can use Flash#setKeepMessages() to let the faces messages survive a redirect (they're namely by default request scoped!). You can use ExternalContext#redirect() to perform a redirect in a non-action method.
So, summarized, this should do:
<h:form id="cform">
...
<f:event type="postValidate" listener="#{bean.postValidate}" />
</h:form>
with:
public void postValidate() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.isValidationFailed()) {
context.getExternalContext().getFlash().setKeepMessages(true);
context.getExternalContext().redirect("contact.xhtml#cform");
}
}
Or we can use f:ajax onerror= for do something if they are an errors :
<p:commandButton **>
<f:ajax onerror="window.scrollTo(0, 0);" />
</p:commandButton>
You don't need an explicit anchor tag for this, the id of the form will do.
You could make Faces render the id at the end of the form action Url.
Eg.
... Your main page content goes here ....
<form id="contact-form" action="/MyView.jsf#contact-form" method="post">
This will cause the browser to scroll to the form after it is submitted.
It shows in the Url too.
You could probably implement a custom Form renderer to do this.

Set default value of input field while using EL statement to read value

So my team has a jsf and we use an EL statement to read in the value of an input box, works fine but by default we have our value set as what should be filled into the field. How can I set a default value for the input while still having the EL statement work.
Example:
<h:inputText value="#{registrationBean.firstName}" styleClass="formEle"/>
I tried
<h:inputText value="#{registrationBean.firstName}First Name" styleClass="formEle"/>
but this breaks the connection when we submit.
Any ideas?
You're looking for something which is called a "watermark" or "placeholder". At low level, these days this is normally to be done by the HTML5 placeholder attribute:
<input type="text" placeholder="First Name" />
This works of course only in browsers supporting HTML5 and then only with JSF components supporting the new HTML5 attribute. The standard JSF <h:inputText> doesn't support this natively (yet). You'd need to look for 3rd party component libraries supporting this. Among them is PrimeFaces with its <p:watermark>:
<h:inputText id="firstName" value="#{registrationBean.firstName}" />
<p:watermark for="firstName" value="First Name" />
If using PrimeFaces is not an option for some reason, you'd need to reinvent it yourself in flavor of a custom component and/or a custom piece of JS/jQuery, exactly like <p:watermark> is doing under the covers.
You could define default value of <h:inputText> in your backing bean in PostConstrut phase.
#ManagedBean(name="registrationBean")
public class RegistrationBean{
private String firstName;
#PostConstruct
public void init(){
firstName = "your default value";
}
}
After page creation value displayed in h:inputText will be as you defined in backing bean.
It's kind of work around without any third party library maybe it will help someone.
The HTML-Tags rendered by JSF can be modified by JavaScript after loading inserting a placeholder attibute for HTML5:
<script>
window.onload = function() {
document.getElementById('email').setAttribute("placeholder", "Email");
document.getElementById('pwd').setAttribute("placeholder", "Password");
}
</script>
If you decide to use PrimeFaces you are not required to use a watermark, see example below:
<h:form>
<p:panel id="panel" header="Client Details" style="margin-bottom:10px;">
<p:messages id="messages" />
<h:panelGrid columns="2">
<h:outputLabel for="firstName" value="First Name" />
<p:inputText id="firstName" value="#{clientlistpagebean.selectedFieldClient.firstName}" required="true" />
<p:outputLabel for="lastName" value="Last Name" />
<p:inputText id="lastName" value="#{clientlistpagebean.selectedFieldClient.lastName}" required="true" />
</h:panelGrid>
</p:panel>
<p:commandButton value="Submit" update="panel" style="margin-right:20px;" />
</h:form>

JSF passing in expression value into a commanButton

I am trying to access the value of the expression $result.id and use that value and pass it in the bean action commitBtn. how do I go about doing this.
<c:forEach items="${bean.results}" var="result">
<fieldset>
<legend>
<b>Title:</b>
${result.id}
<c:set var="Id" value="${result.id}" />
<!-- this Id doesn't show as well, why -->
<h:outputText value="#{Id}" binding="#{bean.Id_lbl}" id="iD_lbl" />
<h:commandButton value="Commit" binding="#{bean.commitBtn}"
id="commitBtn" action="#{bean.commitBtn}" />
</legend>
...
Use the <f:param> tag to pass the value to the action. Within the action you will have to get the param value from the requestMap
something like:
<h:commandButton blah blah blah>
<f:param name="resultId" value="${result.id}" />
</h:commandButton>
then in action code:
resultId = FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("resultId");
The f:param as some may suggest does not work in a h:commandButton in JSF 1.x. Use f:setPropertyActionListener instead:
<h:commandButton value="Commit" binding="#{bean.commitBtn}" id="commitBtn" action="#{bean.commitBtn}">
<f:setPropertyActionListener target="#{bean.resultId}" value="#{result.id}" />
</h:commandButton>
Also see this article for more hints.

Resources