Search code examples
formsapiweb2py

web2py form creation


I'm trying to create a form in web2py. I'm not sure on the correct syntax and don't understand from the examples in the site how this is done. Could someone give a better explanation?

How is a simple form like this created?

<form> 
<select> 
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input type="text" /> 
<input type="submit" />
</form>

How can I validate more complex forms?


Solution

  • items = ['Paint','Brushes','Erasers']
    form = FORM(
        SELECT(*items),
        INPUT('Quantity', _type='text'),
    )
    
    return dict(form=form)
    

    (in view):

    {{ extend 'layout.html' }}
    
    {{ =form}}
    

    To validate this form, or a "more complex" form:

    (in controller)

     form = FORM(...) # This is the same form def as above, must be before form.process() 
    
     if form.process().accepted:
         # Valid!
     else:
         # invalid. 
    

    If you have a more specific question, I'll attempt to answer it, but I highly recommend you check out the book and try to create and validate your own simple forms. You can use the welcome app as a place to start. Or you could google around for web2py apps and download and play with them.

    Read these two chapters in their entirety and I'll help you with anything web2py in the future (there will be a quiz!):

    Database Abstraction layer (important for unlocking the full power of web2py's DB-driven forms): http://web2py.com/books/default/chapter/29/6

    Forms and Validators (everything you ever needed to know about creating forms and linking it to data: http://web2py.com/books/default/chapter/29/7