1.8.6 Typed Fields Example

##
1.8.6 Typed Fields Example

As an example showing the how to use the typed fields, not the use of `None` values.

    #!/usr/bin/env python

    "Forms example."

    import sys, re, os
    sys.path.append('../')
    sys.path.append('../../')
    import web.error; web.error.handle(handler='browser', output='debug', format='html')
    import web, web.form, web.form.field.basic, web.util
    import web.form.field.typed

    class ExampleForm(web.form.Form):

        def setup(self):
            self.addField(web.form.field.basic.Input('input', 'Default Text', 'Input Box:', size=14, maxlength=25))
            self.addField(web.form.field.typed.String('string', default=None, treatNullStringAsNone=False))
            self.addField(web.form.field.typed.String('string None', default=None, treatNullStringAsNone=True))
            self.addField(web.form.field.typed.Bool('bool', required=True))
            self.addField(web.form.field.typed.Bool('bool None', default=None))
            self.addField(web.form.field.typed.Text('text', default=None, treatNullStringAsNone=False))
            self.addField(web.form.field.typed.Text('text None', default=None, treatNullStringAsNone=True))
            self.addField(web.form.field.typed.Integer('integer', default=None, required=True))
            self.addField(web.form.field.typed.DateTime('datetime', default=None, required=True))
            self.addField(web.form.field.typed.StringSelect('stringselect', options=[None, 'String'], displayNoneAs=''))
            self.addField(web.form.field.typed.FloatSelect('floatselect', options=[None, 1]))
            self.addField(web.form.field.typed.FloatCheckBoxGroup('floatcheckboxgroup', options=[1,5.89]))
            # The preffered way of adding submit buttons is as actions so Submit buttons are normally not used.
            self.addAction('Validate This Form')

        def valid(self):
            if web.form.Form.valid(self):
                validates = True
                if self.get('input').value == 'Default Text':
                    self.get('input').setError("ERROR: You must change the text in the input box.")
                    validates = False
                return validates
            else:
                return False

    # Print the HTTP Header
    print web.header('text/html')

    # Create a form
    exampleForm = ExampleForm('form', 'webserver-web-form-typed.py', 'get')

    if len(web.cgi) > 0: # Form submitted
        # Populate form with the values from get.

        # Prepare form values:
        values = {}

        for k in web.cgi.keys():
            values[k] = [k,str(web.cgi[k])]
            if exampleForm.has_key(k):
                values[k].append(exampleForm[k].value)
                values[k].append(exampleForm[k].error())
        exampleForm.populate(web.cgi)

        for k in web.cgi.keys():
            if exampleForm.has_key(k):
                values[k].append(exampleForm[k].value)
                values[k].append(exampleForm[k].error())

        if exampleForm.valid():
            for k in web.cgi.keys():
                if exampleForm.has_key(k):
                    values[k].append(exampleForm[k].value)
                    values[k].append(exampleForm[k].error())
            valueText = ''
            for k in exampleForm.keys():
                if web.cgi.has_key(k):
                    valueText += '<strong>%s</strong><br>'%values[k][0]
                    valueText += '<table border="0">'
                    valueText += '<tr><td>Create</td><td>%s</td></tr>'%web.encode(repr(values[k][2]))
                    valueText += '<tr><td>Error</td><td>%s</td></tr>'%web.encode(repr(values[k][3]))
                    valueText += '<tr><td>Populate</td><td>%s</td></tr>'%web.encode(repr(values[k][4]))
                    valueText += '<tr><td>Error</td><td>%s</td></tr>'%web.encode(repr(values[k][5]))
                    valueText += '<tr><td>Validate</td><td>%s</td></tr>'%web.encode(repr(values[k][6]))
                    valueText += '<tr><td>Error</td><td>%s</td></tr>'%web.encode(repr(values[k][7]))
                    valueText += '</table><br><br>'
            print "<html><head><title>Form Test - Validated</title></head><body>\n<h1>It Validated!</h1>%s\n<hr>\n<h2>Values</h2>%s</body></html>"%(exampleForm.frozen(), valueText)
        else:
            for k in web.cgi.keys():
                if exampleForm.has_key(k):
                    values[k].append(exampleForm[k].value)
                    values[k].append(exampleForm[k].error())
            valueText = ''
            for k in exampleForm.keys():
                if web.cgi.has_key(k):
                    valueText += '<strong>%s</strong><br>'%values[k][0]
                    valueText += '<table border="0">'
                    valueText += '<tr><td>Create</td><td>%s</td></tr>'%web.encode(repr(values[k][2]))
                    valueText += '<tr><td>Error</td><td>%s</td></tr>'%web.encode(repr(values[k][3]))
                    valueText += '<tr><td>Populate</td><td>%s</td></tr>'%web.encode(repr(values[k][4]))
                    valueText += '<tr><td>Error</td><td>%s</td></tr>'%web.encode(repr(values[k][5]))
                    valueText += '<tr><td>Validate</td><td>%s</td></tr>'%web.encode(repr(values[k][6]))
                    valueText += '<tr><td>Error</td><td>%s</td></tr>'%web.encode(repr(values[k][7]))
                    valueText += '</table><br><br>'
            print "<html><head><title>Form Test - Errors</title></head><body>\n<h1>Please Check Entries</h1>%s\n<hr>\n<h2>Values</h2>%s</body></html>"%(exampleForm.html(), valueText)
    else:

        print "<html><head><title>Form Test</title></head><body>\n<h1>Welcome Please Fill In The Form</h1>%s\n<hr></body></html>"%(exampleForm.html())

You can test this example by starting the test webserver in scripts/webserver.py and visiting http://localhost:8080/doc/src/lib/webserver-web-form-typed.py on your local machine.