How can I change the way GRAILS GSP fieldValue formats Integers? - grails

I have a field in my domain object which I define as an Integer...
Integer minPrice
I then access it in a GSP page as follows:
${fieldValue(bean: myBean, field: 'minPrice')}
and what I get in my HTML is...
100,000
which is not an Integer, it's a String. Worse still it's a formatted String in a particular locale.
This is a problem because I have a SELECT control on an HTML FORM which has a (non-ordinal) range of values for minPrice which I want to store in my domain object as integers, and I don't want to store an index to some array of values that I have to repeatedly map back and forth between, I want the value itself.
My select control looks like this...
<g:select name="minPrice"
value="${fieldValue(bean: personInstance, field: 'minPrice')}"
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
['name':'100,000', 'id':100000],
['name':'200,000', 'id':200000],
['name':'300,000', 'id':300000]
]}"
optionKey="id" optionValue="name"
/>
When I get the value from the SELECT field to post back to the server it correctly has an Integer value, which I persist. However the return trip never pre-selects the right row in the drop-down because the value is this comma separated String.
This works fine elsewhere in my code for small numbers where the comma formatting doesn't come into play, and the round-trip in and out of the SELECT is successful. But values >999 don't work.
The docs say "This tag will inspect a bean which has been the subject of data binding and obtain the value of the field either from the originally submitted value contained within the bean's errors object populating during data binding or from the value of a bean's property. Once the value is obtained it will be automatically HTML encoded."
It's that last bit that I want to avoid as it appears to format Integers. So, what little bit of Grails/GSP magic do I need to know so I can get my Integer to be rendered as an integer into my SELECT and pre-select the right row?
EDIT:
I have tried some further things based on the answers below, with pretty disappointing results so far...
If I put the <gformatNumber/> tag in my <g:select/> I get the page code as text in the browser.
<g:select name="minPrice"
value='<g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />'
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
['name':'100,000', 'id':100000],
['name':'200,000', 'id':200000],
['name':'300,000', 'id':300000],
]}"
optionKey="id" optionValue="name"
/>
Using the number format tag from GSP on my Integer value of 100000 like this...
var x = <g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />;
gives 100. Remember that the fieldValue gives back 100,000, so this is not a surprise.
If I use the jsp taglib like this...
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
var y = <fmt:formatNumber value="${fieldValue(bean: personInstance, field: 'minPrice')}" pattern=".00"/>;
I get an error from the page compiler Cannot format given Object as a Number.
I guess I have a wider concern than I can't seem to get an Integer value as a genuine integer into my code if it is greater than 999 because of the default (and unconfigurable) behaviour of the fieldValue directive. However my specific problem of not being able to pre-select an Integer value in a SELECT control is not going away. At the moment I'm at a bit of a loss.
Anyone have any further ideas?

Do you want to show the raw number? like 100000?
You can get the field directly:
${myBean.minPrice}

I think you have at least two possible solutions.
One is to use the JSTL taglib as described in the docs.
Another, cooler way is to use the 'formatNumber' tag included with grails - also in the docs.
For your purpose, the use of that tag might look like this:
<g:formatNumber number="${fieldValue(bean: myBean, field: 'minPrice')}" format="######" />

Use the 'groupingUsed' attribute in combination with your format:
<g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}"
format="#"
groupingUsed="true" />

Better use custom PropertyEditor in order not to bother with formatNumber tag every time you output a value.
Like, declare a bean in resources.groovy:
myOwnCustomEditorRegistrar(CustomEditorRegistrar)
And create your class:
class CustomEditorRegistrar implements PropertyEditorRegistrar {
void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(BigDecimal.class, new MyBigDecimalEditor(BigDecimal.class))
}
}

Change
var x = <g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}" format="#" />;
to
var x = <g:formatNumber number="${personInstance.minPrice}" format="#" />;

I found the best way to handle this was doing what Victor Sergienko (upped btw) hinted at with using a PropertyEditor.
Create an editor for Integer, put in src/groovy:
class IntegerEditor extends PropertyEditorSupport {
void setAsText(String s) {
if (s) value = s as Integer
}
public String getAsText() {
value
}
}
and register it using a PropertyEditorRegistrar (also in src/groovy):
class MyEditorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry reg) {
reg.registerCustomEditor(Integer, new IntegerEditor())
}
}
add your registrar into the spring config (grails-app/conf/spring/resource.groovy):
beans = {
customEditorRegistrar(MyEditorRegistrar)
}
From now on any Integers that are bound, receive errors (or not) and then redisplayed with the fieldValue tag should be displayed by Integer's default toString - you can customise this behaviour in the editor by amending the getAsText implementation.
Personally I would create a wrapper for this kind of thing so you can set up an editor just for that type rather than across the board for a frequently used type. Though I realise this would mean a little bit of mapping when persisting to the DB...

I have a solution/work-round... The answer seems to be, "do nothing".
Instead of trying to parse the stringified number back into an integer, I left it as a formatted string for the purposes of the select. This meant I had to change my from values as follows:
<g:select name="minPrice"
value="${fieldValue(bean: personInstance, field: 'minPrice')}"
onchange="setDirty()"
noSelection='${['0':'Select a number...']}'
from="${[
['name':'100,000', 'id':'100,000'],
['name':'200,000', 'id':'200,000'],
['name':'300,000', 'id':'300,000']
]}"
optionKey="id" optionValue="name"
/>
Of course when I post back to the server the value that gets sent is "100,000" as an escaped String. What I realised was that Grails, or Spring, or Hibernate, or something in the stack, would do the coersion of the String back into the right Integer type prior to persistence.
This works just fine for my purposes, however I think it is basically a work-round rather than a solution because of locale issues. If my thousand separator is a "." and my decimal separator is ",", which it is for much of Europe, then my code won't work.

Use like this :
<g:formatNumber number="${fieldValue(bean: personInstance, field: 'minPrice')}"
format="#.##"/>;

Related

Svelte input binding breaks when a reactive value is a reference type?

(I'm new to Svelte so it is quite likely that I'm doing something wrong here)
UPDATE: I've added a second, slightly different REPL which may demonstrate the problem better. Try this one: https://svelte.dev/repl/ad7a65894f8440ad9081102946472544?version=3.20.1
I've encountered a problem attempting to bind a text input to a reactive value.
I'm struggling to describe the problem in words, so hopefully a reduced demo of the issue in the attached REPL will make more sense.
https://svelte.dev/repl/6c8068ed4cc048919f71d87f9d020696?version=3.20.1
The demo contains two custom <Selector> components on a page.
The first component is passed two string values ("one" and "two"):
<Selector valueOne="one" valueTwo="two"/>
Clicking the buttons next to the input field sets selectedValue to one of these values.
This, in turn, triggers the following reactive declaration to update:
$: value = selectedValue
The input field is bound to this reactive value:
<input type="text" bind:value>
So clicking the "One" button sets the input text to "one", and clicking the "Two" button sets the input field to "two".
Importantly though, you can still type anything into the input field.
The second component is passed two array values:
<Selector valueOne={[1, "one"]} valueTwo={[2, "two"]}/>
Again, clicking the buttons sets selectedValue to one of these.
However this time the reactive declaration depends on an array element:
$: value = selectedValue[1]
Everything works as before, except now you can no longer type into the input field at all.
So the question is - why does <input bind:value> behave differently for these two:
$: value = aString
vs
$: value = anArray[x]
It seems that this is only an issue when using two-way bindings.
By switching to a one-way and an on:input handler, the problem goes away:
i.e. instead of this:
<input type="text" bind:value={valX}/>
use this:
<input type="text" value={valX} on:input={e => valX = e.target.value}/>
I'm pretty sure your reactive declaration is overwriting your bound value as soon as it changes, which is with every key stroke on the input and every button press. Meaning it technically is working, you're just reverting it each time it changes. Check out this version of it that uses a watcher.
Also binding to a reactive declaration means you're never actually changing the variables with the input (which you can see in your JSON result on the first selector when you type in the input the value doesn't update only on button click).
Why not lose the reactive declaration and bind directly to the variable you want. Then use an {#if} block to switch between which version of the input you're showing based on the truthiness of index?
<script>
export let valueOne;
export let valueTwo;
export let index;
let selectedValue = index? [] : '';
let selectValue = (val) => selectedValue = val;
</script>
{#if index}
<input type="text" bind:value={selectedValue[index]} placeholder="Type anything...">
{:else}
<input type="text" bind:value={selectedValue} placeholder="Type anything...">
{/if}
<button on:click={() => selectValue(valueOne)}>One</button>
<button on:click={() => selectValue(valueTwo)}>Two</button>
<p>
<strong>Selected value:</strong> {JSON.stringify(selectedValue)}
</p>
By binding directly to the selectedValue or an index of it you have the added benefit of changing the value with the input. Here's a working example in the REPL

Evaluate Groovy/Grails Code in variable when printing it in GSP

I have a GSP page containing different input elements related to a specific context.
For example I can display a textfield for usecase A, but not for usecase B (short version, it's very complex actually)
For this I have a domain object, which is normally populated with plain static HTML. But now I need to add dynamic data, like this:
def field = new InputField()
field.code = '<input type="text" name="foo" value="${currentUser.name}" />'
// or: field.code = '<option value="1"><g:message code="someCode"/></option>'
This code is stored in database. It will be rendered later on in GSP:
<g:each in="${InputField.findAllBySomeCondition(...)}">
${it.code}
</g:each>
This will print the input element, but instead of evaluating the dynamic code (${currentUser.name}) it is just printed as plain text.
Unfortunately I can't change the whole process, there are over 3000 different input elements stored already, but none of them are dynamic.
Is there a way to tell Grails to evaluate code within the variable before printing it?
edit: I'm using Grails 2.2.4
That's because you're using ' for the string, not ". When using ' the result is a String, not a GString with variable evaluation.
Try changing to:
field.code = "<input type=\"text\" name=\"foo\" value=\"${currentUser.name}\" />"
or use the triple version """ to avoid escaping:
field.code = """<input type="text" name="foo" value="${currentUser.name}" />"""

Grails : Use value from session in drop down list option

In my controller:
def billingDetails() {
def traineeDetails = session.traineeDetais
println "session data::"+traineeDetails
[traineeNames:traineeDetails.name]
}
This prints: [numberOfTrainees:2, submit_trainee_details:Next: Billing Details �, phone:[999999, 99999], email:[tester1#test.com, tester2#test.com], name:[Jack, Rob], jobTitle:[SE, SE], action:processTraineeDetails, controller:trainingOrder]
now in my GSP i want to have a select tag which will have name (jack, Rob) as options
<g:select name="traineeName"
from="${traineeNames}"
value=""
/>
which is not working fine.. How to make this to work so that i will get the names as options in dropdown list
make use of the optionKey optionValue fields in your g:select
reference:
http://grails.org/doc/2.2.1/ref/Tags/select.html
and do something like
<g:select optionKey="value" optionValue="value"
name="traineeName" from="${traineeNames}" />
I don't know the exact problem but one possible reason is that your session.traineeDetais.name is not a list. Check weather session.traineeDetais.name is a list or not, like
println "Check: ${session.traineeDetais.name instanceof List}"
if it is list then your code should work and if it is string then your drop down contain string characters as values.

a list of checkboxes

I have two domain classes
class Contract {
String number
static hasMany = [statements:Statement]
}
class Statement {
String code
static hasMany = [contracts:Contract]
}
I would like to show all statements available in my gsp with a checkbox next to each, allowing the user to choose which statements are applicable to the contract. So something like:
[ ] Statement Code 1
[ ] Statement Code 2
[ ] Statement Code 3
I started off with this:
<g:each in="${Statement.list()}" var="statement" status="i">
<g:checkBox name="statements[${i}].id" value="${statement.id}" checked="${contractInstance.statements.contains(statement.id)}" />
<label for="statements[${i}]">${statement.code}</label>
</g:each>
But i just cannot get a list of checked statements to the controller (there are null elements in the list, there are repeated statements...).
Any idea how to achieve this?
This is possible, but it does require a bit of a hack. First off, every checkbox must have the same name, "statements":
<g:each in="${org.example.Statement.list(sort: 'id', order: 'asc')}" var="statement" status="i">
<g:checkBox name="statements" value="${statement.id}" checked="${contract.statements.contains(statement)}" />
<label for="statements">${statement.content}</label>
</g:each>
Second, in the controller you have to remove the "_statements" property before binding:
def contract = Contract.get(params.id)
params.remove "_statements"
bindData contract, params
contract.save(failOnError: true)
The check box support hasn't been designed for this use case, hence the need for a hack. The multi-select list box is the one typically used for this type of scenario.
I personally prefer to get the list of Id's in this case.
<g:each var="book" in="${books}">
<g:checkBox name="bookIds" value="${book.id}" ...
</g:each>
Command Object:
class BookCommand {
List<Serializable> bookIds
}
In controller action:
BookCommand bc ->
author.books = Book.getAll(bc.bookIds)
Change the checkbox to something like this.
<g:checkBox name="statements.${statement.id}" value="true" checked="${contractInstance.statements.contains(statement)?:''}" />
and then in the controller, in params.statements you will get a list with the IDs of the checked statements.
Also notice the ?:'' in the checked property, it's a good idea to add it because any value(even 'false') in the checked property is interpreted as checked.
Are you mapping request directly to Contract? It's much more secure to map incoming request into an Command object.
As about mapping a list - values are mapped only to existing elements. I mean it cannot create new list elements. You need to prepare it before mapping. If you know that there is always 3 elements, you can make:
class ContractCommand {
List statements = [
new Statement(),
new Statement(),
new Statement(),
]
}
and map request to this object

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.

Resources