My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
makeForm  
primitives function for form creation
Deprecated
Updated Feb 4, 2010 by perciou...@gmail.com

makeForm

makeForm provides a function for creating a Toscawidget based on a SQLAlchemy Model.

API

makeForm(model,
         action,
         identifier='',
         identifier='',
         controller='/',
         hiddenFields=[],
         disabledFields=[],
         requiredFields=[], 
         omittedFields=[],
         additionalFields=[],
         limitFields=None,
         fieldAttrs={},
         widgets={},
         validators={}, 
         formWidgetType=None,
         formValidator=None
         checkIfUnique=False)-->Toscawidgets.TableForm
         
Generates an entry form for use in web applications.

Arguments:
name              type                           default    Description
model             class                                     sqlalchemy mapped class definition
action            String                                    string passed to the forms 'action'
identifier        String or None                 None       optional identifier for the form
hiddenFields      list if names                  []         fields that are hidden but not altogether 
                                                            removed from the table, useful for passing 
                                                            data through a form manually.
disabledFields    list of names                  []         fields that are shown but not editable
requiredFields    list of names                  []         fields that cannot be left empty by the user (validation type stuff)
omittedFields     list of names                  []         fields that are not present, whatsoever
additionalFields  list of Toscawidgets.fields    []         fields that you would like to add to the form that are not in the model
limitFields       list of names                  None       limit the fields to the one in the list.  A side effect is that the 
                                                            order of the fields is set by this argument.
                                                            (a good way to order your fields if you include all of them)
fieldAttrs        dict of field Attrs            {}         a set of extra parameters which can be passed into the widgets
                                                            that are created in a form.
widgets           dict of Toscawidgets           {}         a set of widgets linked to your fields by fieldname, you must do your own validation.
validators        dict of formencode.validators  {}         validators linked to fields in your form indexed by fieldname
formWidgetType    ToscaWidget                    None       field for the actual widget to be used
formValidator     Schema or validator            None       validator for the overall form
checkIfUnique     Boolean                        False      adds default validator to "unique" fields to check if the value
                                                            the user has entered is unique or not.
"""

Usage

Here is an more complicated example which expresses some of the features of makeForm. This is the definition for creating a user registration form. The requirements are that the user must enter their username, email and password. The password must be verified. Subsequently, their account will be activated by setting a boolean 'enabled' flag in their account. Thus, the enabled field is omitted, along with the permission-type settings and the creation date as well. These are to be set later by the admistrator, perhaps using DBMechanic.

from dbsprockets.primitives import makeForm
from toscawidgets.widgets.forms.fields import PasswordField
from formencode.validators import FieldsMatch
from formencode import Schema

from mymodel.model import User

requiredFields = ['password', 'user_name', 'email_address']
limitFields  = ['user_name', 'display_name', 'email_address', 'password', ]

additionalFields = [PasswordField('passwordVerification', label_text='Verify'),]
formValidator =  Schema(chained_validators=(FieldsMatch('password',
                                                        'passwordVerification',
                                                        messages={'invalidNoMatch': 
                                                                  "Passwords do not match"}),))

registrationForm = makeForm(User, 
                            'register', 
                            requiredFields=requiredFields, 
                            limitFields=limitFields, 
                            additionalFields=additionalFields, 
                            formValidator=formValidator)

More information about the demoModel .

The town, tg_groups, created, user_id, and enabled forms have been omitted. Not-Empty validators have been added to the password, passwordVerification, user_name and email_address fields. DBSprockets will automatically detect foreign_key and many_to_many relationships, and therefore if we don't want the user to be able to select their own groups we must remove the town and tg_groups fields, even though they are not defined in the table.

The passwordVerification field has been added to test that the user put in the correct password. This is in-turn checked by the formValidator using a chained_validator within a schema.

The result looks like this:

Special note for Turbogears 1.0 Developers

Because of the way TG1 handles form validation, you must make the form validator a FilteringSchema that allows extra fields if you are going to add a custom form validator. Example code for password verification is below:

class FilteringSchema(Schema):
    filter_extra_fields = True
    allow_extra_fields = True

formValidator =  FilteringSchema(chained_validators=(FieldsMatch('password',
                                                                 'passwordVerification',
                                                                 messages={'invalidNoMatch': 
                                                                  "Passwords do not match"}),))

Adding a custom field to the form

So, lets say you don't want a great big box for the email field. You can just substitute the email field with a custom widget. For the time being, you will have to provide your own validator to any field you customize. Here is what the code looks like:

from dbsprockets.primitives import makeForm

from toscawidgets.widgets.forms.fields import PasswordField
from toscawidgets.widgets.forms import TextField

from formencode.validators import FieldsMatch
from formencode.validators import Email

emailField = TextField(id='email_addy', validator=Email())


requiredFields = ['password', 'user_name', 'email_address']
limitFields  = ['user_name', 'display_name', 'email_address', 'password', ]

additionalFields = [PasswordField('passwordVerification', label_text='Verify'),]

formValidator =  Schema(chained_validators=(FieldsMatch('password',
                                                        'passwordVerification',
                                                        messages={'invalidNoMatch': 
                                                                  "Passwords do not match"}),))

registrationForm = makeForm(User, 
                            'registration', 
                            requiredFields=requiredFields, 
                            limitFields=limitFields, 
                            additionalFields=additionalFields,
                            widgets={'email_address':emailField},
                            formValidator=formValidator)

Which results in a registration form like this:

Field Attributes

Now, I think we can all agree that the display_name column is a bit on the silly side, in terms of size. What we can do is to pass field attrs to that column to change its size.

The registration form code now looks like this:

registrationForm = makeForm(User, 
                            'registration', 
                            requiredFields=requiredFields, 
                            limitFields=limitFields, 
                            additionalFields=additionalFields,
                            fieldAttrs={'display_name':{'cols':14, 'rows':1}},
                            widgets={'email_address':emailField},
                            formValidator=formValidator)

And Here is the result:


Sign in to add a comment
Powered by Google Project Hosting