Map<String, String> params = JqueryLookupWidget.decrypt(encodedString);
Configuration cfg = hibernateUtil.getConfiguration();
PersistentClass pc = cfg.getClassMapping(params.get("model"));
ModelForm form = forms.newForm(ModelForm.class);
form.setPrefix("jquery_lookup_form"); // make sure field names don't conflict with something else in the form.
Class<?> clazz = pc.getMappedClass();
form.setModel(clazz);
String fields = params.get("search");
String fieldName = params.get("field");
String display = params.get("display");
String results = params.get("results"); // URLDecoder.decode(params.get("results"), "UTF-16");
String orderBy = params.get("order_by");
String[] resultColumns = results.split(",");
context.put("StringFormat", new StringFormat()); // needed in the template to format the display
context.put("field_name", fieldName);
context.put("field_list", resultColumns);
context.put("display", display);
context.put("prompt_data", URLEncoder.encode(encodedString, "UTF-8"));
// fields may have joins or header information, parse
List<String> modelFields = new ArrayList<String>(); // list of fields that come directly from the model
Map<String,Field<String>> addFormFields = new HashMap<String, Field<String>>(); // map of form fields to add to the form
for(String field : fields.split(",")) {
field = field.trim();
String[] parts = field.split(":");
if (parts.length == 1) {
modelFields.add(field);
} else { // this field has title information included.
// Verbose Name:field__join__searchtype
// Yes this means that in order for joins to be used the field must have a custom name TODO
// parts[0] = verboseName
// parts[1] = field
Field<String> formField = fieldFactory.newField(CharField.class)
.setAllowNull(true)
.setRequired(false)
.setName(parts[1])
.setVerboseName(parts[0]);
addFormFields.put(parts[1],formField);
}
}
if (!modelFields.isEmpty()) {
form.setInclude(modelFields.toArray(new String[]{}));
} else {
form.setInclude("");
}
form.getFields().putAll(addFormFields);
for(Field f : form.getFields().values()) {
f.setRequired(false).setAllowNull(true);
}
if (search) {
context.put("form_url", String.format("%s/%s", request.getContext(), request.getPath()));
Map<String, String[]> searchParams = new HashMap<String, String[]>(request.getParameterMap());
if (searchParams.containsKey("page")) searchParams.remove("page");
if (searchParams.containsKey("prompt_data")) searchParams.remove("prompt_data");
form.bind(request.getParameterMap());
if (form.isValid()) {
int page;
try {
page = new Integer(request.getParameter("page"));
} catch (NumberFormatException e) {
page = 1;
}
Manager<?> manager = managers.forClass(clazz);
QuerySet<?> qs = manager.filter(form.getCleanedData());
if (orderBy != null) {
qs = qs.orderBy(orderBy);
} else if (resultColumns != null && resultColumns.length > 0) {
qs = qs.orderBy(resultColumns);
}