Reset form values onload in bootsfaces - java

I need to reset the form fields and clear the form values onload.
However I used -
public void refresh() {
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
ViewHandler viewHandler = application.getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(context, context
.getViewRoot().getViewId());
context.setViewRoot(viewRoot);
context.renderResponse(); //Optional
}
The above code is working but when I am entering values in fields using in panelgroup , its not working.
<h:panelGroup>
<ui:repeat value="#{formDynAttrbBean.vals}" var="values">
<b:panelGrid columns="6" cellspacing="4">
<b:inputText id="label" value="">
</b:inputText>
<b:selectOneMenu value="">
<f:selectItem itemLabel="SelectType" itemValue="" />
<f:selectItems value="" />
</b:selectOneMenu>
<b:selectBooleanCheckbox value="" />
<b:commandButton actionListener="#{form.types}" />
</b:panelGrid>
</ui:repeat>
<b:commandButton tooltip="Add new attribute" tooltip-position="bottom"
iconAwesome="plus" actionListener="#{form.add}" update="#form" />
<tr />
<b:commandButton value="Save" ajax="true"
actionListener="#{form.submit}" update="#form" />
<tr />
<b:commandButton type="reset" action="#{formController.refresh}"
value="Reset">
</b:commandButton>
</h:panelGroup>
Refresh function is not working in this case when I am entering values in panelgroup and in repeating fields.
I am just a beginner to bootsfaces.Please suggest me an approach.Thankyou in advance.

There are ways to clear the input fields of the form. For example, JSF 2.2 has the resetValues="true" attribute (see the article of Michael Kurz (probably not implemented by BootsFaces). Another option is to use <b:commandButton type="reset">.
But I wonder why you want to reset the values on the client side? You have to clear them because they display some "dirty" (i.e. modified) backend bean. IMHO the better approach is to create a new, empty backend bean.

Related

Updating non-JSF form

I have a situation where I am suppose to submit a user's payment details to my payment gateway partner.
For this I have a separate non JSF form with hidden values as parameters to be passed.
<form id="hiddenForm" action="#{checkoutBean.payuAction}" method="post" name="payuForm">
<p:outputPanel id="hiddenPanel">
<h:inputHidden id="hash" value="#{checkoutBean.hash}"/>
<h:inputHidden id="txnid" value="#{checkoutBean.txnid}"/>
<h:inputHidden id="amount" value="#{checkoutBean.totoalAmount}"/>
<h:inputHidden id="firstname" value="#{checkoutBean.firstname}"/>
<h:inputHidden id="email" value="#{checkoutBean.email}"/>
<h:inputHidden id="phone" value="#{checkoutBean.phone}"/>
<h:inputHidden id="productinfo" value="#{checkoutBean.productInfo}"/>
<h:inputHidden id="surl" value="#{checkoutBean.sURL}" />
<h:inputHidden id="furl" value="#{checkoutBean.fURL}"/>
</p:outputPanel>
</form>
The above hidden values are generated using ajax at the last step in a wizard (primefaces). The ajax call is happening but I am unable to update the non JSF form. The values are null.
<p:commandButton value="Confirm" actionListener="#{checkoutBean.initPayu}" onsuccess="submitPayuForm()" update=":hiddenForm:hiddenPanel" />
The above button is in a <h:form>.
Now i believe that it is not possible to update non JSF components from JSF components. But I just can't figure out how to tackle this scenario.
Any ideas on how I can tackle this problem?
Using : JSF 2 , Primefaces 3.3
Thanks a ton in advance.
Since your form is not a JSF component you don't need to append its id to ids of your JSF components (:hiddenForm:hiddenPanel).
In other words, try something like this:
<p:commandButton ... update="hiddenPanel" />

Composite-Component within a form that requires interaction/validation

A quick background : I have put a captcha using the primefaces custom component on my website. People in charge don't like it as it is too difficult to use and clients are/were complaining. I decided I wanted to create a simple component (ie: 4 + 9 = and user inputs the answer) to avoid a bit of spam. No need to have an image display the question, just using simple text. This got me looking into custom components and composite component ( from this article and this one ).
Now, the question is not so much about a makeshift basic "captcha style validation". It's more about a composite component and backing bean combo.
What I would do is create a backing bean in this style :
<cc:interface>
<cc:attribute name="label" />
<!-- edited -->
<cc:attribute name="required" />
<cc:attribute name="ident" />
</cc:interface>
<cc:implementation>
<h:panelGrid columns="3">
<h:outputText value="#{captcha.text}"/>
<h:inputText id="#{cc.attrs.ident}" value="#{captcha.entered}" validator="#{captcha.validate}" required="#{cc.attrs.required eq 'true'}" label="#{cc.attrs.label}" />
<h:message for="captchaAnswer" />
</h:panelGrid>
<h:inputHidden value="#{captcha.value}" />
</cc:implementation>
And then I'd like to use this component in this manner :
<h:form>
...
<tr>
<td>
<my:captcha label="Captcha" ident="captcha" required="true"/> <!-- added after suggested comment -->
<br/>
<h:message for="captcha" class="error"/>
</td>
</tr>
<tr>
<td colspan="3" class="center">
<h:commandButton class="button" value="#{msg['contact.label.send']}" action="#{contact.send}" >
</h:commandButton>
</td>
</tr>
...
</h:form>
How can I make sure that on submit I can check that my {#captcha.entered} value is the required value and if not returns a validation message on the form and prevents it from being submitted?
captcha backing bean would be simple and have values : text, answer, and, entered and a simple function to check if answer == entered.
EDIT : (Attempt #1)
custom validator would look as follow
public void validate(FacesContext context, UIComponent toValidate, Object value) {
System.out.println("validating");
String input = (String) value;
//check to see if input is an integer
//if not we know right away that the value is not good
if(StringUtils.isNumeric(input)) {
//if the input is numeric, convert to an integer
int intValue = new Integer(input).intValue();
if (intValue != answer) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Not a match!!");
context.addMessage(toValidate.getClientId(context), message);
}
}
}
In this instance the validator does not even get called and I don't get an error message.
Edit #2
After a bit of working and hints from comments I got this working. To get the h:message working I needed to add the attribute ident instead of id. If not I had to reference it as so : <h:message for="captcha:captcha" /> which was not the desired outcome.
The primary issue with this question was that I couldn't get a reference.
By adding the attribute ident instead of id I got this to work. Please refer to edit #2 in question.

Assign dynamic ids to hidden fields when iterating over a collection

Is there a way to assign dynamic ids to h:inputHidden components?
EDIT1
I am trying to assign the ids inside a ui:repeat tag when iterating over a collection of elements.
It is not possible to set the ID based on the iteration value of an <ui:repeat>. But you don't need it anyway. They will by default already get dynamic and unique IDs based on the iteration index.
E.g.
<h:form id="form">
<ui:repeat value="#{bean.list}" var="item">
<h:inputHidden id="hidden" value="#{item.value}" />
</ui:repeat>
</h:form>
will generate this HTML during view render time
<form id="form" name="form">
<input type="hidden" id="form:0:hidden" name="form:0:hidden" value="item1value" />
<input type="hidden" id="form:1:hidden" name="form:1:hidden" value="item2value" />
<input type="hidden" id="form:2:hidden" name="form:2:hidden" value="item3value" />
</form>
If you want to manually control the ID, you'd need to use <c:forEach> instead, because <ui:repeat> doesn't generate multiple JSF components, but lets its children (which is a single <h:inputHidden> in the above example) generate HTML multiple times. The <c:forEach> will generate multiple JSF components which then each generate HTML only once (so you effectively end up with multiple <h:inputHidden> components in JSF component tree).
E.g.
<h:form id="form">
<c:forEach items="#{bean.list}" var="item">
<h:inputHidden id="#{item.id}" value="#{item.value}" />
</c:forEach>
</h:form>
which will basically generate this JSF component tree during view build time
<h:form id="form">
<h:inputHidden id="item1id" value="#{bean.list[0].value}" />
<h:inputHidden id="item2id" value="#{bean.list[1].value}" />
<h:inputHidden id="item3id" value="#{bean.list[2].value}" />
</h:form>
which in turn will generate this HTML during view render time
<form id="form" name="form">
<input type="hidden" id="form:item1id" name="form:item1id" value="item1value" />
<input type="hidden" id="form:item2id" name="form:item2id" value="item2value" />
<input type="hidden" id="form:item3id" name="form:item3id" value="item3value" />
</form>
See also:
JSTL in JSF2 Facelets... makes sense?
They get assigned a dynamic ID by default. You can also specify id="#{..} to customize it.
You can dynamically add any random number also (id="#{}"),but
add functionally related ids to hidden components, that will be helpful
for example if it is employee form ,you may add empid to it.

Retrieve values from JSP to Javascript

Below is the javascript on my JSP page:
<SCRIPT language="JavaScript">
function checkPass(){
var pass1=request.getParameter('password');
var pass2=request.getParameter('password2');
if (pass1==pass2){
window.alert("YES");
}
else{
window.alert("NO");
}
}
</SCRIPT>
Below is my form input text boxes:
<h:outputLabel value="Password:" for="password" />
<h:inputSecret id="password" value="#{StaffController.staff.password}"
size="20" required="true"
label="Password" >
<f:validateLength minimum="8" />
</h:inputSecret>
<h:message for="password" style="color:red" />
<h:outputLabel value="Password:" for="password2" />
<h:inputSecret id="password2"
size="20" required="true"
label="Password" >
<f:validateLength minimum="8" />
</h:inputSecret>
<h:message for="password2" style="color:red" />
Below is my commandbutton linked with onmousedown to call the script when clicked:
<h:commandButton action="#{StaffController.saveUser()}" onmousedown="checkPass();" value="Submit"/>
I can't seem to retrieve value from my user input form.
JSF changes id of components - view source of your page in browser. It should be something like a combination of form id+component id
Submit command invokes onmousedown event before making submit, so in checkPass you do not have a request object
Better to write a custom validator for checking password
First you require to set in the h:form the value false to the "prependId" attribute to make possible to get the textboxes by id on javascript. Is not recomended to remove the prependId. But it makes to you easier to work with javascript. In other way you could use a field name or css name an other kind of selection (like using Jquery $('.cssname') or $('#cssid')
Now you need to change the javascript. javascript is performed on the client side. You can't get data from the request because the request is not done when the javascript is executed.
You need to get the inputSecret object ,that in the html is an input item, using something like this:
var pass1 = document.getById('password').value;
var pass2 = document.getById('password2').value;

Passing Parameters With Seam, RichFaces & PopupPanel

I'm trying to get a little application working using Seam 3, RichFaces 4 and hitting a few troubles with passing some parameters around. I've tried a lot of different things but I keep falling at the final hurdle. I'm carrying through a customerId via a request parameter. But when I hit a RichFaces commandButton on a popupPanel, that customerId is no longer available to me.
I'm setting up an application to manage some data. Basically you select a customer from one screen, that will take you to another screen containing "repositories" where you then can create, edit etc. You can get to this second repositories page via the URL:
http://localhost:8080/media-manager/repositories.xhtml?customer=12
I then have a bean picking this value up:
#Named
#RequestScoped
public class RepositoryBean extends AbstractViewBean<Repository> {
// Various properties etc. here
private Long customerId;
public void init() {
log.info("Customer ID is "+ customerId);
}
}
I then set the customer ID via metadata on the repository page and call init:
<f:metadata>
<f:viewParam name="customer" value="#{repositoryBean.customerId}"/>
<f:event type="preRenderView" listener="#{repositoryBean.init}" />
</f:metadata>
This works well at the start. I can display information I need for the customer with the supplied ID. But when I try to create my popupPanel is goes a bit wrong. Here's a simplified version of the code first:
<rich:popupPanel id="repositoryModalPanel" modal="true" resizeable="true">
<f:facet name="header">Title</f:facet>
<f:facet name="controls">
<h:outputLink value="#" onclick="#{rich:component('repositoryModalPanel')}.hide(); return false;">X</h:outputLink>
</f:facet>
<h:form id="modalForm" class="modalForm">
<fieldset>
<ul class="layout form">
<li>
<label for="name" class="required">Name:</label>
<h:inputText id="name" value="#{repositoryBean.instance.name}" required="true">
<!-- rich:validator event="blur" / -->
</h:inputText>
<rich:message for="name" errorClass="error errormessage" />
</li>
<li class="last">
<a4j:commandButton id="create" value="Create" action="#{repositoryBean.saveRepository}" rendered="#{empty repositoryBean.instance.id}"/>
<a4j:commandButton id="save" value="Save" action="#{repositoryBean.saveRepository}" rendered="#{not empty repositoryBean.instance.id}"/>
<a4j:commandButton id="cancel" value="Cancel" action="#{repositoryBean.clearInstance}" immediate="true" />
</li>
</ul>
</fieldset>
</h:form>
Basically, whenever I hit the save commandButton, the init method is called but the customerId member is never populated. Does anyone have any insight into why?
I've read that viewParam is only for GET requests so maybe that's the problem? But if that's the case - what is the other solution? Lots of things I have seen suggested (e.g. using #ManagedProperty) does not seem to be applicable to Seam 3.
RepositoryBean is RequestScoped, and as such will be newly created on each request, especially if you hit the save button.
The straightforward solution is to promote RepositoryBean to be ConversationScoped, and to make it long running if you enter the page.
#Named
#ConversationScoped
public class RepositoryBean extends AbstractViewBean<Repository> {
// Various properties etc. here
#In
Conversation conversation
private Long customerId;
public void init() {
log.info("Customer ID is "+ customerId);
conversation.begin();
}
}
The easieast way for that is to dump the preRenderView and use seam 3 view-action instead.
<f:metadata>
<f:viewParam name="customer" value="#{repositoryBean.customerId}"/>
<s:viewAction action="#{repositoryBean.init}" if="#{conversation.transient}"/>
</f:metadata>

Categories