2
votes

I created a taglib to shorten input field code. It presets 'name', 'value' and others. Now I need to get a bean value, but the field holding that value is dynamic.
See some code (shortened to better work out my problem):

gsp:

<g:validatedInputField bean="${command}" field="surname" />
<g:validatedInputField bean="${command}" field="name" />

taglib

def validatedInputField = { attrs, body ->

    def field = attrs.field
    def bean = attrs.bean

    if (field && bean) {

        def val = bean.field
        out << "<input type=\"text\" name=\"$field\" bean=\"$bean\" value=\"$val\">"
    }
}

So the problem is the following line. It does obviously not work because there is no field 'field' in the bean. I want it to be dynamically replaced by 'name' or 'surname' or whatever the value of the param 'field' is.

def val = bean.field

I tried exprimenting with various GString/interpolation variations, but nothing worked.
Of course I could just add another param to pass the value, but I feel like it shouldn't be required as I already have everything I need to get it in the taglib...

Can you please give me some directions?
Thanks

2

2 Answers

1
votes

In groovy, you can refer to a member of an object dynamically by using GStrings. For example:

def val = bean."${field}"

You could even perform some logic inside the GString. Let's say you have a default field and you want to use the name inside the 'field' variable only if it is not null:

def val = bean."${field ? field : "default"}
1
votes

If bean is an object instance and field is a String that represent a member of that object, you can try something like:

def val = bean."$field"