0001"""
0002Forms expect the defaults to be either single values or lists of values. The values from ``cgi.FieldStorage()`` aren't quite suitable.
0003# XXX Write a converter function
0004"""
0005from formbuild.builder import Builder
0006
0007class FieldsBuilder(Builder):
0008 """
0009 The base class of all FormBuild extensions that add methods to a form attribute.
0010 """
0011
0012 def __init__(self):
0013 self.type = 'fields'
0014
0015 def __call__(self, form):
0016 self._form = form
0017
0018 def _encode(self, s):
0019 translations = {"&": "&", '"': """, "<": "<", ">": ">"}
0020 l = list(str(s))
0021 for i in range(len(l)):
0022 c = l[i]
0023 l[i] = translations.get(c, c)
0024 return "".join(l)
0025
0026
0027 def _attributes(self, attributes):
0028 output = ''
0029 for key in attributes.keys():
0030 output += ' %s="%s"' % (key, attributes[key])
0031 return output
0032
0033 def option(self, option, selected_values):
0034
0035 if isinstance(option, tuple) or isinstance(option, list):
0036 (value, label) = option
0037 else:
0038 (value, label) = (option, option)
0039 selected = ""
0040 if not (isinstance(selected_values, tuple) or isinstance(selected_values, list)):
0041 selected_values = [selected_values]
0042 for v in selected_values:
0043 if str(v) == str(value):
0044 selected = ' selected="selected"'
0045 break;
0046 return '<option value="%s"%s>%s</option>' % (value, selected, label)
0047
0048 def options(self, options, selected_values):
0049 mode = 'value'
0050 if isinstance(options[0], tuple) or isinstance(options[0], list):
0051 mode = 'list'
0052 counter = 1
0053 result = ''
0054 for option in options:
0055 if mode=='list':
0056 (value, label) = counter, option
0057 else:
0058 (value, label) = option
0059 counter += 1
0060 selected = ""
0061 if not (isinstance(selected_values, tuple) or isinstance(selected_values, list)):
0062 selected_values = [selected_values]
0063 for v in selected_values:
0064 if str(v) == str(value):
0065 selected = ' selected="selected"'
0066 break;
0067 result += '<option value="%s"%s>%s</option>\n' % (value, selected, label)
0068 return result