Cloudream
Cloudream

Reputation: 651

How to read annotation value in play framework templates?

I want to use values from annotation in CRUD module templates, to utilize HTML5 functions.

e.g.

@Range(min=0, max=10)

public int size;

CRUD module use views/tags/crud/numberField.html to display number field:

#{field 'object.' + _name}
    <label for="${field.id}">
        &{_name}
    </label>
    <input id="${field.id}" type="text" name="${field.name}" value="${params[field.name]?.escape()?.raw() ?: field.error?.message == 'validation.required' ? '' : _value?.escape()?.raw()}" size="5" />
    #{ifError field.name}
        <span class="error">${field.error}</span>
    #{/ifError}
#{/field}

How can I read min/max value from annotation then output as min="0" max="0" in <input> ?

Upvotes: 2

Views: 1078

Answers (3)

Peter Hilton
Peter Hilton

Reputation: 17344

You can do this by adding methods to the CRUD module's CRUD.ObjectType.ObjectField inner class that read the annotation values, e.g. something like:

public String getRangeMin() {
    if (!property.field.isAnnotationPresent(Range.class)) {
        return null;
    }
    return property.field.getAnnotation(Range.class).min();
}

Then in crud/views/tags/crud/form.html you can use this in a new tag parameter inside the #{if field.type == 'number'} (note that field is a CRUD.ObjectType.ObjectField here:

#{crud.numberField min:field.min …

The value is then available as _min inside the numberField.html tag.

Upvotes: 2

Pere Villega
Pere Villega

Reputation: 16439

in the Validation sample included in Play!, Sample #7 includes some Jquery code that reads the annotations in a class and uses them for Javascript validation. I believe that should help you.

Upvotes: 0

seb
seb

Reputation: 1810

You have to write a FastTag for that. Since this is all Java you can use reflection to query your objects for annotations in there. If you want to use it exclusive for validation you could let the html5validation module to do that for you.

Upvotes: 1

Related Questions