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

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}" />"""

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

How to insert '_' as htmlAttributes in razor?

This is probably a simple question, but to which I havent found an answer yet.
How to escape the ' _ ' when creating an HtmlElement in razor?
To render a '-' in the final Html we put an ' _ ', but to render an '_' (underscore), How do we escape it? I tryed '#:', but it didn't work, and didn't find any other options...
Example:
#Html.CheckBox("Access_Groups", false, new
{
#class = "input-control checkbox",
#data_group = "I', looking for data-group",
#Description_pt = "<----- I'm looking for Description_pt"
})
#data_group will render as data-group as expected, but...
#Description_pt will render as Description-pt, and that is not what is expected (don't know how to escape the _ for this)
thank you
If you look at the signature of Html.Checkbox, we can see that it takes an object for the htmlAttributes. Further, looking at the syntax, its actually a key based collection of objects. A Dictionary<string,object> fits that bill and allows you to absolutely specify the name of the html attributes that you want to add (note each key is typed exactly how we want it to display).
#Html.CheckBox("Access_Groups", false, new Dictionary<string,object>
{{"class", "input-control checkbox"},
{"data-group", "I', looking for data-group"},
{"Description_pt", "SomeValue"}})
This renders the following HTML
<input Description_pt="SomeValue" class="input-control checkbox"
data-group="I', looking for data-group" id="Access_Groups"
name="Access_Groups" type="checkbox" value="true" />
Have you tried the HTML character code for underscore, i.e., _?

data being passed from controller, is it encoded?

I want to ask in MVC3+; data passed from controller in form of modle or viewbag is the data encoded by default or I do have to ?
Do you mean HTML encoded? They're not, no.
This means that if you have a string property that contains the value "<b>some text</b>" then the property contents is exactly that.
If, however, you try to print this output to the View with #MyProperty then, by default, the string will be HTML-encoded by MVC. So the output would become <some text>.
You can escape this by using #Html.Raw(MyProperty).
Remember that the term 'encoded' is a bit vague. Try to be specific with what encoding you're referring to.
MVC proactively tries to encode values to prevent cross-site scripting.
#* This is HTML Encoded *#
#Model.Value
#* This value is not encoded *#
#Html.Raw(Model.Value)
#* The URL gets URL Encoded *#
<a href="#Url" />
This Razor code
# {
bool disabled = false;
bool readonly = true;
string className = null;
}
<input type="text" disabled="#disabled" readonly="#readonly" class="#className" />
Actually produces this output
<input type="text" readonly="readonly" />
A value of null or false causes the Razor view engine to not render the attribute at all.
If you did want something like this data-soldout="false" then you need to do:
data-soldout="#Html.Raw(isSoldout)" or data-soldout="#isSoldout.ToString()"

how to pass params using action button in grails

been having toruble with the button that has action. I have several btns which I want to know its paramaeter. In grails tutorial it says it should be like this:
<g:actionSubmit action="action" value="${message(code: 'default.button.edit.label', default: 'Edit')}" params="['actionTaken':editPhone]"/>
I tried using remotelink, submitButton, submitToRemote tags but none works. I always get null when I try parsing it in my controller:
def action=
{
def actionTaken = params.actionTaken
def employeeId= params.employeeId
MySession session = MySession.getMySession(request, params.employeeId)
profileInstance = session.profileInstance
switch(actionTaken)
{
case "editPhone" :
isEditPhone=true
break
case "editEmail" :
isEditEmail=true
break
}
render(view:"profile", model:[profileInstance:session.profileInstance, isEditPhone:isEditPhone, isEditEmail:isEditEmail])
}
What am I missing? is my params code wrong? Is my code in parsing params wrong? this just gets me in circles with no progress. help. thanks.
The Grails documentation doesn't list params as one of the attributes accepted by actionSubmit.
It is possible to inject the value you want in your params list in the controller by exploiting what that tag actually does:
def editPhone = { forward(action:'action', params:[actionTaken: 'editPhone'])}
def editEmail = { forward(action:'action', params:[actionTaken: 'editEmail'])}
You may also just want to just code completely separate logic into the editPhone and editEmail actions if that makes your code cleaner.
Updated View Code:
<g:actionSubmit action="editPhone" value="${message(code: 'default.button.edit.label', default: 'Edit')}" />
The params attribute is parsed as a map, where the keys are treated a strings but the values are treated as expressions. Therefore
params="['actionTaken':editPhone]"
is trying to define the key named actionTaken to have the value from the variable named editPhone in the GSP model. Since there is no such variable you're getting null. So the fix is to move the quotes:
params="[actionTaken:'editPhone']"
which will set the value to the string "editPhone".
You could also pass the parameter inside the POST-data using
<input type="hidden" name="actionTaken" value="editPhone" />
inside the form. Then it is also accessible through the params variable.
It works for me.
I just had a similar problem (I needed to submit a delete together with an id) and found a solution using HTML5's "formaction" attribute for submit-inputs.
They can be given a value that can include a controller, action, additional parameters, etc.
In General, to add a parameter to a submit button such as a edit of a specific sub-object on a form would looks like this:
<input type="submit" formaction="/<controller>/<action>/<id>?additionalParam1=...&additionalParam2=..." value="Action" >
and in your example:
<input type="submit" formaction="action?actionTaken=editPhone" value="${message(code: 'default.button.edit.label', default: 'Edit')}" >
In my situation, I had a single form element with multiple actions on each row of a table (i.e. data table edit buttons). It was important to send the entire form data so I couldn't just use links. The quickest way I found to inject a parameter was with javascript. Not ideal, but it works:
function injectHiddenField(name, value) {
var control = $("input[type=hidden][name='" + name + "']");
if (control.size() == 0) {
console.log(name + " not found; adding...");
control = $("<input type=\"hidden\" id=\"" + name + "\" name=\"" + name + "\">");
$("form").append(control);
}
control.val(value);
}
Your button can look like this:
<g:each in="${objects}" var="object">
...
<g:actionSubmit value="edit" action="anotherAction"
onclick="injectHiddenField('myfield', ${object.id})"/>
</g:each>

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

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="#.##"/>;

Resources