# -*- mode: python -*- # -*- coding: utf-8 -*- """Simple form generator/validator E. Viennet 2005 - 2008 v 1.2 """ from types import BooleanType, StringType, UnicodeType def TrivialFormulator( form_url, values, formdescription=(), initvalues={}, method="post", enctype=None, submitlabel="OK", name=None, formid="tf", cssclass="", cancelbutton=None, submitbutton=True, submitbuttonattributes=[], top_buttons=False, # place buttons at top of form bottom_buttons=True, # buttons after form html_foot_markup="", readonly=False, is_submitted=False, ): """ form_url : URL for this form initvalues : dict giving default values values : dict with all HTML form variables (may start empty) is_submitted: handle form as if already submitted Returns (status, HTML form, values) status = 0 (html to display), 1 (ok, validated values in "values") -1 cancel (if cancelbutton specified) HTML form: html string (form to insert in your web page) values: None or, when the form is submitted and correctly filled, a dictionnary with the requeted values. formdescription: sequence [ (field, description), ... ] where description is a dict with following (optional) keys: default : default value for this field ('') title : text titre (default to field name) allow_null : if true, field can be left empty (default true) type : 'string', 'int', 'float' (default to string), 'list' (only for hidden) readonly : default False. if True, no form element, display current value. convert_numbers: covert int and float values (from string) allowed_values : list of possible values (default: any value) validator : function validating the field (called with (value,field)). min_value : minimum value (for floats and ints) max_value : maximum value (for floats and ints) explanation: text string to display next the input widget title_buble: help bubble on field title (needs bubble.js or equivalent) comment : comment, showed under input widget withcheckbox: if true, place a checkbox at the left of the input elem. Checked items will be returned in 'tf-checked' attributes: a liste of strings to put in the HTML form element template: HTML template for element HTML elements: input_type : 'text', 'textarea', 'password', 'radio', 'menu', 'checkbox', 'hidden', 'separator', 'file', 'date', 'boolcheckbox', 'text_suggest' (default text) size : text field width rows, cols: textarea geometry labels : labels for radio or menu lists (associated to allowed_values) vertical: for checkbox; if true, vertical layout disabled_items: for checkbox, dict such that disabled_items[i] true if disabled checkbox To use text_suggest elements, one must: - specify options in text_suggest_options (a dict) - HTML page must load JS AutoSuggest.js and CSS autosuggest_inquisitor.css - bodyOnLoad must call JS function init_tf_form(formid) """ method = method.lower() if method == "get": enctype = None t = TF( form_url, values, formdescription, initvalues, method, enctype, submitlabel, name, formid, cssclass, cancelbutton=cancelbutton, submitbutton=submitbutton, submitbuttonattributes=submitbuttonattributes, top_buttons=top_buttons, bottom_buttons=bottom_buttons, html_foot_markup=html_foot_markup, readonly=readonly, is_submitted=is_submitted, ) form = t.getform() if t.canceled(): res = -1 elif t.submitted() and t.result: res = 1 else: res = 0 return res, form, t.result class TF: def __init__( self, form_url, values, formdescription=[], initvalues={}, method="POST", enctype=None, submitlabel="OK", name=None, formid="tf", cssclass="", cancelbutton=None, submitbutton=True, submitbuttonattributes=[], top_buttons=False, # place buttons at top of form bottom_buttons=True, # buttons after form html_foot_markup="", # html snippet put at the end, just after the table readonly=False, is_submitted=False, ): self.form_url = form_url self.values = values self.formdescription = list(formdescription) self.initvalues = initvalues self.method = method self.enctype = enctype self.submitlabel = submitlabel if name: self.name = name else: self.name = formid # 'tf' self.formid = formid self.cssclass = cssclass self.cancelbutton = cancelbutton self.submitbutton = submitbutton self.submitbuttonattributes = submitbuttonattributes self.top_buttons = top_buttons self.bottom_buttons = bottom_buttons self.html_foot_markup = html_foot_markup self.readonly = readonly self.result = None self.is_submitted = is_submitted if readonly: self.top_buttons = self.bottom_buttons = False self.cssclass += " readonly" def submitted(self): "true if form has been submitted" if self.is_submitted: return True return self.values.get("%s-submitted" % self.formid, False) def canceled(self): "true if form has been canceled" return self.values.get("%s_cancel" % self.formid, False) def getform(self): "return HTML form" R = [] msg = None self.setdefaultvalues() if self.submitted() and not self.readonly: msg = self.checkvalues() # display error message R.append(tf_error_message(msg)) # form or view if self.readonly: R = R + self._ReadOnlyVersion(self.formdescription) else: R = R + self._GenForm() # return "\n".join(R) __str__ = getform __repr__ = getform def setdefaultvalues(self): "set default values and convert numbers to strings" for (field, descr) in self.formdescription: # special case for boolcheckbox if descr.get("input_type", None) == "boolcheckbox" and self.submitted(): if field not in self.values: self.values[field] = 0 else: self.values[field] = 1 if field not in self.values: if "default" in descr: # first: default in form description self.values[field] = descr["default"] else: # then: use initvalues dict self.values[field] = self.initvalues.get(field, "") if self.values[field] == None: self.values[field] = "" # convert numbers if type(self.values[field]) == type(1) or type(self.values[field]) == type( 1.0 ): self.values[field] = str(self.values[field]) # if "tf-checked" not in self.values: if self.submitted(): # si rien n'est coché, tf-checked n'existe plus dans la reponse self.values["tf-checked"] = [] else: self.values["tf-checked"] = self.initvalues.get("tf-checked", []) self.values["tf-checked"] = [str(x) for x in self.values["tf-checked"]] def checkvalues(self): "check values. Store .result and returns msg" ok = 1 msg = [] for (field, descr) in self.formdescription: val = self.values[field] # do not check "unckecked" items if descr.get("withcheckbox", False): if not field in self.values["tf-checked"]: continue # null values allow_null = descr.get("allow_null", True) if not allow_null: if val == "" or val == None: msg.append( "Le champ '%s' doit être renseigné" % descr.get("title", field) ) ok = 0 # type typ = descr.get("type", "string") if val != "" and val != None: # check only non-null values if typ[:3] == "int": try: val = int(val) self.values[field] = val except: msg.append( "La valeur du champ '%s' doit être un nombre entier" % field ) ok = 0 elif typ == "float" or typ == "real": self.values[field] = self.values[field].replace(",", ".") try: val = float(val.replace(",", ".")) # allow , self.values[field] = val except: msg.append( "La valeur du champ '%s' doit être un nombre" % field ) ok = 0 if typ[:3] == "int" or typ == "float" or typ == "real": if "min_value" in descr and val < descr["min_value"]: msg.append( "La valeur (%d) du champ '%s' est trop petite (min=%s)" % (val, field, descr["min_value"]) ) ok = 0 if "max_value" in descr and val > descr["max_value"]: msg.append( "La valeur (%s) du champ '%s' est trop grande (max=%s)" % (val, field, descr["max_value"]) ) ok = 0 # allowed values if "allowed_values" in descr: if descr.get("input_type", None) == "checkbox": # for checkboxes, val is a list for v in val: if not v in descr["allowed_values"]: msg.append( "valeur invalide (%s) pour le champ '%s'" % (val, field) ) ok = 0 elif descr.get("input_type", None) == "boolcheckbox": pass elif not val in descr["allowed_values"]: msg.append("valeur invalide (%s) pour le champ '%s'" % (val, field)) ok = 0 if "validator" in descr: if not descr["validator"](val, field): msg.append("valeur invalide (%s) pour le champ '%s'" % (val, field)) ok = 0 # boolean checkbox if descr.get("input_type", None) == "boolcheckbox": if int(val): self.values[field] = 1 else: self.values[field] = 0 # open('/tmp/toto','a').write('checkvalues: val=%s (%s) values[%s] = %s\n' % (val, type(val), field, self.values[field])) if descr.get("convert_numbers", False): if typ[:3] == "int": self.values[field] = int(self.values[field]) elif typ == "float" or typ == "real": self.values[field] = float(self.values[field].replace(",", ".")) if ok: self.result = self.values else: self.result = None return msg def _GenForm(self, method="", enctype=None, form_url=""): values = self.values add_no_enter_js = False # add JS function to prevent 'enter' -> submit # form template # default template for each input element itemtemplate = """