webmcp
view framework/env/ui/autofield.lua @ 401:ad437022be90
Quick fix to avoid problems on document creation
author | jbe |
---|---|
date | Mon Jan 04 00:48:47 2016 +0100 (2016-01-04) |
parents | 9fdfb27f8e67 |
children |
line source
1 --[[--
2 ui.autofield{
3 name = name, -- field name (also used by default as HTML name)
4 html_name = html_name, -- explicit HTML name to be used instead of 'name'
5 value = nihil.lift(value), -- initial value, nil causes automatic lookup of value, use nihil.lift(nil) for nil
6 container_attr = container_attr, -- extra HTML attributes for the container (div) enclosing field and label
7 attr = attr, -- extra HTML attributes for the field
8 label = label, -- text to be used as label for the input field
9 label_attr = label_attr, -- extra HTML attributes for the label
10 readonly = readonly_flag -- set to true, to force read-only mode
11 record = record, -- record to be used, defaults to record given to ui.form{...}
12 ... -- extra arguments for applicable ui.field.* helpers
13 }
15 This function automatically selects a ui.field.* helper to be used for a field of a record.
17 --]]--
19 function ui.autofield(args)
20 local args = table.new(args)
21 assert(args.name, "ui.autofield{...} needs a field 'name'.")
22 if not args.record then
23 local slot_state = slot.get_state_table()
24 if not slot_state then
25 error("ui.autofield{...} was called without an explicit record to be used, and is also not called inside a form.")
26 elseif not slot_state.form_record then
27 error("ui.autofield{...} was called without an explicit record to be used, and the form does not have a record assigned either.")
28 else
29 args.record = slot_state.form_record
30 end
31 end
32 local class = args.record._class
33 assert(class, "Used ui.autofield{...} on a record with no class information stored in the '_class' attribute.")
34 local fields, field_info, ui_field_type, ui_field_options
35 fields = class.fields
36 if fields then
37 field_info = fields[args.name]
38 end
39 if field_info then
40 ui_field_type = field_info.ui_field_type
41 ui_field_options = table.new(field_info.ui_field_options)
42 end
43 if not ui_field_type then
44 ui_field_type = "text"
45 end
46 if not ui_field_options then
47 ui_field_options = {}
48 end
49 local ui_field_func = ui.field[ui_field_type]
50 if not ui_field_func then
51 error(string.format("Did not find ui.field helper of type %q.", ui_field_type))
52 end
53 for key, value in pairs(ui_field_options) do
54 if args[key] == nil then
55 args[key] = value
56 end
57 end
58 return ui_field_func(args)
59 end