How to reset input value if a condition fails Primefaces3.5 - jsf-2

I have a problem. I am trying to save a information into the database, and before that I check some conditions like if-else like:
if(condition){
//Some Action
}else{
getFacesContext().addMessage(null,MessageFactory.getMessage(ResourceBundle.FACES_BUNDLE.getName(), FacesBundle.LANDLINE_NUMBER_SHOULD_BE_TEN.getName()));
getExternalContext().getFlash().setKeepMessages(true);
return;
}
and When the condition does not match I would like to restore the previous values of the input field.
In that case, it was 22 in place of ss. but the field does not take input except numbers. So the validation fails and shows an message Invalid Input via growl.
How can I also reset the value of the field ss to 22 in java?
Please suggest!

You can use default validator that comes with JSF
<p:inputText id="number" value="" label="Number">
<f:validateDoubleRange minimum="0" maximum="99" />
</p:inputText>
<p:message for="number" />
But if you reset the filed with old value, user may not know what he's entered. However you will not submit until validation success.

Since the input text component implements EditableValueHolder you can call EditableValueHolder.resetValue() on the input component (or call the more convenient RequestContext.getCurrentInstance().reset(inputTextId)) and then re-render it by calling RequestContext.getCurrentInstance().update(inputTextId) if it isn't already being re-rendered through the update attribute of p:ajax.

Related

playwright-test: test that input is required

I have an input for a login form that is required:
<input
autoComplete="email"
defaultValue={email}
disabled={state === 'submitting'}
id="email"
name="email"
placeholder={t('user-authentication:email-placeholder')}
required // HERE!
type="email"
/>
How can I test that the input is required with Playwright? My native browser warning in Chromium is: "Please fill in this field."
Is there a way to check / assert for this warning in Playwright? Or another way to test that the input is required?
I tried writing nothing in the input with .fill('') and then pressing enter with page.keyboard.press('Enter'), but those did not cause the warning to show up.
If the message is displayed by the browser and not something added to the DOM, you would struggle to test it directly in Playwright.
You could check the the required attribute is present, and trust that the browser is going to display the warning.
await page.locator('input#email[required]')
There's also a Constraint validation you could apply
If the element is required and the element's value is the empty string, then the element is suffering from valueMissing and the element will match the :invalid pseudo class.
await page.locator('input#email[required]:invalid')

h:selectBooleanCheckbox not getting set with correct value

Versions :
Aapche MyFaces 2.1.14
RichFaces 4.3.5
Issue :
I am facing very strange issue for JSF2.1
As shown in code snippet at the end , boolean check box is disabled based on boolean variable #{bean.disabled}.
The issue is below :
1)First #{bean.disabled} evaluates to false so checkbox is enabled.
User clicks the checkbox and submits the form (form is not shown here )
2)The action method sets the disabled = true and required= true and same page is rendered again
3)At this stage , UI has check box clicked and disabled. When at this stage , form is
submitted again , bean.setRequired method is called with setter value as FALSE whereas it should set it with value as TRUE
4)When I made disabled="#{false}" , this issue vanished and bean.setRequired method is called with setter value as TRUE
So question is why is the behaviour in step 3 observed even though UI is showing check box in clicked condition (meaning it has a value as TRUE , i also printed the
bean.required value and is evaluating to TRUE only
Code :
<h:panelGroup>
<h:selectBooleanCheckbox id="invite" disabled="#{bean.disabled}" value="#{bean.required}" />
<h:outputText value="Do Update"/>
</h:panelGroup>
Make sure the backing property bound to #{bean.disabled} is a boolean and not a string for which values "TRUE" and "FALSE" are being set.
Also, the behavior you described in step 3 is expected. When the checkbox is disabled, the value submitted will always be false since browsers normally ignore disabled fields during form submit. To make sure you get the right value, maintain a hidden field alongside the checkbox, keep both of them in sync and use the value of the hidden field instead to test if the checkbox is checked or unchecked. Something like below:
<h:selectBooleanCheckbox id="invite" disabled="#{bean.disabled}" value="#{bean.required}" />
<h:inputHidden id="inviteHidden" value="#{bean.requiredHidden}" />
// While setting values, set values for both fields inside the action method
bean.setRequired(true); // ..or false
bean.setRequiredHidden(true); // ..or false
// And to test whether checkbox is checked, do...
if(bean.isRequiredHidden()) {
....
}
Unrelated to your question, if you're using the <c:set/> for conditional rendering, consider using <a4j:outputPanel rendered = "#{someCondition}"/> instead and on your form submit update it (if it is an AJAX submit.

Value not retained for action parameter when inside ui:repeat

Below is my Code:
<ui:repeat var="status" value="#{showUpdatedAction.statusUpdates}">
<h:panelGroup>
#{status.content}
<h:form>
<h:commandLink value="Like" action="#{statusAction.likeStatus(status.id,1)}" />
</h:form>
</h:panelGroup>
<ui:repeat>
#{status.content} shows correct values. When I print id of status using #{status.id}, it also gives correct value. But when I click the command link, value passed is always 0 for status.id.
Can someone tell me why this happens and how can I avoid this?
Thank you.
Edit 1
Interestingly, when instead of passing the parameter in function, I pass it using <f:param>, it works perfectly. Can anyone comment on that?
I think you should try using <c:forEach> instead of <ui:repeat>.
I can't tell you exactly, why status.id is 0 in your case but you can directly pass the whole status object in your EL expression. Like so:
<h:commandAction value="Like" action="#{statusAction.likeStatus(status)}" />
Then in your likeStatus you simply do a int statusId = status.getId() or similar and you have what you want.
As an addition: Using <c:forEach> should actually be just a fallback, because people say you shouldn't mix JSTL with JSF for whatsoever reasons.
Your code in the JSF page is just fine, just checked it... (generated the beans at my side too : showUpdatedAction, statusAction , and a simple class Status)
public void likeStatus(String id,long someVal){
System.out.println(id+"___"+someVal);
}
which prints the ids just fine
id1___1
id4___1
Maybe its something to do with the type of the id or something with your beans?

asp.net mvc checkbox inconsistency

I'm using an checkbox on an ASP.NET MVC form like so:
<%=Html.CheckBox("AgreeToRules", Model.AgreeToRules)%>
The AgreeToRules property on the model is a boolean value. During testing, this all worked fine. However, now that we've gone live with this app, I'm seeing a relatively small but significant number of errors with the following messaging:
System.Web.HttpUnhandledException:
Exception of type
'System.Web.HttpUnhandledException'
was thrown. --->
System.InvalidOperationException: The
parameter conversion from type
'System.String' to type
'System.Boolean' failed. See the inner
exception for more information. --->
System.FormatException: Y is not a
valid value for Boolean. --->
System.FormatException: String was not
recognized as a valid Boolean.
This appears to happen when the view engine tries to render the form after a post, and the value of the checkbox that is returned from the ValueProvider looks like:
Y,false
OR
N,false
The html that is rendered in the original form looks like:
<input id="AgreeToRules" name="AgreeToRules" type="checkbox" value="true" />
<input name="AgreeToRules" type="hidden" value="false" />
During testing, I expected (and showed) the posted value to look like:
true,false
if checked or
false
if not checked. So where is the N and Y coming from?
I added user agent to the list of information returned from the error handler and it appears (so far) that all of the errors are occuring under windows XP with FF 3.0.10, but that's exactly what I have tested with and the problem did not exist during testing.
Any thoughts?
We had this same issue on a project I'm working on (MVC 2). We solved it by replacing the helper with plain html code:
Before:
<%= Html.CheckBox("Credit", false, new {#validate = "required"}) %>
After:
<input type="checkbox" name="Credit" value="true" validate="required" />
<input type="hidden" name="Credit" value="false" />
It's quite possible that your site is being hit by spambots that are submitting this value, and not real users. The more sites I add automated logging and emailing to, the more of these types of "probes" and errors (though not exactly the type you mention, with a "Y" for a checkbox) that I see piling into my inbox. Does your logging also capture the rest of the submitted form contents?
Today I came up with a solution for a similar problem that could be perhaps be adapted to fit your particular need. It will "do the job" for what you are asking, but may not be the most reusable solution.
The idea is that you will walk through the posted form fields and fix the "broken" checkbox values. You can create a ValueProviderDictionary a.k.a. IDictionary<string, ValueProviderResult> and then hand that to your UpdateModel method.
public static IDictionary<string, ValueProviderResult> CreateScrubbedValueProvider(NameValueCollection postedForm, string[] checkboxFieldsToScrub)
{
Dictionary<string, ValueProviderResult> dict = new Dictionary<string, ValueProviderResult>();
foreach (string key in postedForm.AllKeys) {
string[] values = postedForm.GetValues(key);
if (checkboxFieldsToScrub.Contains(key)) {
// Ensure we have a "true" value instead of "Y" or "YES" or whatever...
// Note that with a checkbox, only the first value matters, so we will only
// worry about values[0] and not values[1] (the "unchecked" value, if exists).
if (values[0] == "Y" || values[0] == "YES") {
values[0] = "true";
}
}
string value = String.Join(",", values);
ValueProviderResult vpr = new ValueProviderResult(values, value, null);
dict.Add(key, vpr);
}
return dict;
}
Your controller will need to accept a NameValueCollection (or FormCollection) in its parameters, and you'll need to hand your generated ("scrubbed") value provider dictionary to the UpdateModel method. I haven't tested this exactly, but my version of this is working very similarly for me. Best of luck!
Well I found the problem, and thought I'd post it here in case others encounter it. Certain form fillers will detect the fields using the names I've used and try to "fill them" automatically by setting the value to whatever the user has previously used for similarly named fields. Starting late last night, I'm also receiving "UNSUBSCRIBED" and "SUBSCRIBED" as values for a checkbox named "OptIn".
So, the form filler changes the value of the checkbox to something and the user checks the box, resulting in the unexpected value being transmitted to the server.
Any thoughts on dealing with this would be appreciated.

Grails: checkbox not being set back to false

I am developing a Grails (1.0.4) app where I want to edit a collection of collections on a single page in a grid view. I got it to work quite well depending only on the indexed parameter handling of Spring MVC, except for one thing:
boolean (or, for that matter, Boolean) values in the grid can be set via checkbox, but not unset, i.e. when I check the checkbox and update, the value is set to true, but afterwards when I edit again, uncheck the checkbox and update, it remains true.
This is the GSP code of the checkbox:
<g:checkBox name="tage[${indexTag}].zuweisungen[${indexMitarb}].fixiert" value="${z.fixiert}" />
And this is the HTML that is generated:
<input type="hidden" name="tage[0].zuweisungen[0]._fixiert" />
<input type="checkbox" name="tage[0].zuweisungen[0].fixiert" checked="checked" id="tage[0].zuweisungen[0].fixiert" />
I've found a Grails bug that describes exactly this effect, but it's marked as fixed in 1.0.2, and the problem mechanism described there (underscore in hidden field name is put in the wrong place) is not present in my case.
Any ideas what could be the reason?
This is the solution a guy named Julius Huang proposed on the grails-user mailing list. It's reusable but relies on JavaScript to populate a hidden field with the "false" response for an unchecked checkbox that HTML unfortunately does not send.
I hack GSP to send "false" when
uncheck the box (true -> false) with
custom TagLib.
By default checkBox send nothing when
uncheck, so I use the checkBox as
event handler but send hidden field
instead.
"params" in Controller can handle
"false" -> "true" without any
modification. eg. Everything remain
same in Controller.
The Custom Tag Usage in GSP (sample usedfunc_F is "true"),
<jh:checkBox name="surveyList[${i}].usedfunc_F" value="${survey.usedfunc_F}"></jh:checkBox>
Here is what the Tag generate,
<input type="hidden" name="surveyList[#{i}].usedfunc_F" id="surveyList[#{i}].usedfunc_F" value="false" />
<input type="checkbox" onclick="jhtoggle('surveyList[#{i}].usedfunc_F')" checked="checked" />
The Javascript
<script type="text/javascript">
function jhtoggle(obj) {
var jht = document.getElementById(obj);
jht.value = (jht.value !='true' ? 'true' : 'false');
}
</script>
This is my own solution, basically a workaround that manually does what the grails data binding should be doing (but doesn't):
Map<String,String> checkboxes = params.findAll{def i = it.key.endsWith("._fixiert")} // all checkboxes
checkboxes.each{
String key = it.key.substring(0, it.key.indexOf("._fixiert"))
int tagIdx = Integer.parseInt(key.substring(key.indexOf('[')+1, key.indexOf(']')))
int zuwIdx = Integer.parseInt(key.substring(key.lastIndexOf('[')+1, key.lastIndexOf(']')))
if(params.get(key+".fixiert"))
{
dienstplanInstance.tage[tagIdx].zuweisungen[zuwIdx].fixiert = true
}
else
{
dienstplanInstance.tage[tagIdx].zuweisungen[zuwIdx].fixiert = false
}
}
Works, requires no change in grails itself, but isn't reusable (probably could be made so with some extra work).
I think that the simplest workaround would be to attach a debugger and see why Grails is failing to populate the value. Considering Grails is open source you'll be able to access the source code and once you figure out the solution for it you can patch your version.
I have also found this other bug GRAILS-2861 which mentions the issue related to binding to booleans (see Marc's comment in the thread). I guess that is exactly the problem you are describing.
I would create a small sample app that demonstrates the problem and attach it to the Grails bug (or create a new one). Someone here may be able to debug your sample app or you'll have shown the bug isn't really fixed.
Try this out, set the logs to DEBUG, frist try the first 3 if they don't show the problem up, flip them all to DEBUG:
codehaus.groovy.grails.web.servlet="error" // controllers
codehaus.groovy.grails.web.pages="error" // GSP
codehaus.groovy.grails.web.sitemesh="error" // layouts
codehaus.groovy.grails."web.mapping.filter"="error" // URL mapping
codehaus.groovy.grails."web.mapping"="error" // URL mapping
codehaus.groovy.grails.commons="info" // core / classloading
codehaus.groovy.grails.plugins="error" // plugins
codehaus.groovy.grails.orm.hibernate="error" // hibernate integration
This should allow you to see exactly when and how the parameters setting is failing and probably figure out a work around.

Resources