Source

webmcp / framework / env / ui / field / select.lua

Full commit
--[[--
ui.field.select{
  ...                                 -- generic ui.field.* arguments, as described for ui.autofield{...}
  foreign_records  = foreign_records,  -- list of records to be chosen from, or function returning such a list
  foreign_id       = foreign_id,       -- name of id field in foreign records
  foreign_name     = foreign_name,     -- name of field to be used as name in foreign records
  format_options   = format_options    -- format options for format.string
  disabled_records = disabled_list     -- table of record keys that should be disabled
}

This function inserts a select field in the active slot. For description of the generic field helper arguments, see help for ui.autofield{...}.

--]]--

function ui.field.select(args)
  ui.form_element(args, {fetch_value = true}, function(args)
    local foreign_records = args.foreign_records
    if type(foreign_records) == "function" then
      foreign_records = foreign_records(args.record)
    end
    if args.readonly then
      local name
      for idx, record in ipairs(foreign_records) do
        if record[args.foreign_id] == args.value then
          name = record[args.foreign_name]
          break
        end
      end
      ui.tag{
        tag     = args.tag,
        attr    = args.attr, 
        content = format.string(name, args.format_options)
      }
    else
      local attr = table.new(args.attr)
      attr.name  = args.html_name
      ui.tag{
        tag     = "select",
        attr    = attr,
        content = function()
          if args.nil_as then
            ui.tag{
              tag     = "option",
              attr    = { value = "" },
              content = format.string(
                args.nil_as,
                args.format_options
              )
            }
          end
          for idx, record in ipairs(foreign_records) do
            local key = record[args.foreign_id]
            ui.tag{
              tag     = "option",
              attr    = {
                value    = key,
                disabled = ((args.disabled_records and args.disabled_records[key] and "1" ) or nil),
                selected = ((key == args.value) and "selected" or nil)
              },
              content = format.string(
                record[args.foreign_name],
                args.format_options
              )
            }
          end
        end
      }
    end
  end)
end