Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play! How to retrieve field value in a template tag having entity and the field name passed separately as parameters?

I wanted to create a tag like:

#{some_tag entity:user, field:'name'}

and expect it to produce some output with the user name in it by using expression like:

${_entity._field}

I know it doesn't work but that's why I ask here. Is there a simple way to use a field name passed as a parameter to a template tag to get the field value?

like image 686
Rajish Avatar asked Apr 29 '11 09:04

Rajish


4 Answers

When I needed to do this I did something similar to the CRUD module. I call the tag as #{sometag 'entity.field' /}

then in the fast tag I have (roughly):

String[] parts = args.get("arg").split("\\.");
Object entity = play.mvc.Scope.RenderArgs.current().get(parts[0]);
String field = String.valueOf(parts[1]);
Object value = groovy.util.Eval.me("_caller", template.template, "_caller." + args.get("arg").replace(".", "?."));
like image 91
Brad Mace Avatar answered Oct 05 '22 23:10

Brad Mace


I am not aware of an easy answer, but it is possible. You can create a fast tag, and use reflection to get the field you are after. You can get more info on Fast Tags here - Can someone explain how to use FastTags

However, wouldnt it be easier to just send the specific field through to your tag?

like image 38
Codemwnci Avatar answered Oct 05 '22 23:10

Codemwnci


The parameters are stored in a variable called renderArgs. I'm not sure if this is directly accessible inside templates, but if this doesn't work:

renderArgs.get(_entity)

then you can probably access it indirectly using the static method:

Scope.RenderArgs.current().get(_entity)

Accessing a named field of that entity is then a matter of reflection.

However, I agree with the suggestion that there has to be an easier way. If you find yourself doing reflection like that, it usually (not always) means you've over-engineered something.

like image 37
Marcus Downing Avatar answered Oct 05 '22 22:10

Marcus Downing


You could just pass those parameters to a utility class that uses reflection to find the String value you actually want displayed.

${play.sample.util.ReflectUtil.get(_entity, _field)}

play.sample.util.ReflectUtil:

public static String get(String entity, String field) {
    String displayValue = ... // look up value ... 
    return displayValue;
}

Or a FastTag would work too.

like image 45
Lawrence McAlpin Avatar answered Oct 05 '22 22:10

Lawrence McAlpin