Many websites require <select> form elements that pull their data dynamic. A classic example is a <select> populated with information from a database. RIFE has no native support for dynamic <selects>, but implementing one isn't that difficult. Below is a class that makes the process painless on the template designed and the developer.
package com.warfrog.portal.helpers;
import java.util.List;
import java.util.logging.Logger;
import com.uwyn.rife.engine.Element;
import com.uwyn.rife.template.Template;
import com.uwyn.rife.tools.BeanUtils;
import com.uwyn.rife.tools.exceptions.BeanUtilsException;
public class FormsHelper extends Element {
private FormsHelper() {}
public static void buildSelect(Template dynamicselect, Template template,
String identifier, List beans, String valueProperty,
String displayTextProperty) {
String id = identifier.substring(identifier.lastIndexOf(':') + 1);
dynamicselect.setValue("id", id);
try {
for (Object o : beans) {
dynamicselect.setValue("value", BeanUtils.getPropertyValue(o,
valueProperty));
dynamicselect.setValue("text", BeanUtils.getPropertyValue(o,
displayTextProperty));
dynamicselect.appendBlock("options", "option");
}
} catch (BeanUtilsException e) {
Logger.getLogger("FormHelper").warning(
"Error building the <select>");
}
template.setValue(identifier, dynamicselect);
}
}
Make sure to place the following template in your "template/common" directory as the helper uses the template to build the selects.
<r:v name="select"/>
<r:bv name="select">
<select name="<r:v name="id"/>">
<r:v name="options"/>
</select>
</r:bv>
<r:b name="option">
<option value="<r:v name="value"/>"><r:v name="text"/></option>
</r:b>
To use the class you'd do something like this inside your element:
public class SomeElement extends Element {
public void processElement() {
Template template = getHtmlTemplate("testers.article");
FormsHelper.buildSelect(getHtmlTemplate("common.dynamicselect"), template, "FORM:SELECT:categoryId", new CategoryManager().restore(), "id", "name");
print(template);
}
}
and the sample template
<form name="some_element_data"
action="${v SUBMISSION:FORM:some_element_data/}"
method="post">
<r:v name="SUBMISSION:PARAMS:some_element_data"/>
<r:v name="FORM:INPUT:title"/>
<r:v name="FORM:TEXTAREA:body"/>
<r:v name="FORM:SELECT:someselectelement"/>
<input type="submit"/>
</form>
The code above simply calls FormsHelper.buildSelect(...) with the template to modify, the full name of the select element, a List of beans to work with, the field of the bean to use as the <option> value, and the field of the bean to use as the <option> text. It's that simple.