Personal tools
You are here: Home Documentation Tutorials Working with Forms in Grok Accessing a Form within another View

Accessing a Form within another View

Forms are a specialization of the grok.View base class. You can use a form programmatically from within another View if required.
A walkthrough of the basics of automatically generating HTML forms using Grok, as well as a discussion of a few more advanced Form manipulations.
Page 9 of 9.

All Forms subclass from grok.View, so they can be instantiated and rendered programmatically, just like any other View.

Let's say that you wanted to embed MammothForm within another View. You can simply instantiate the form, passing it the same context and request objects that your View was instantiated with.

class FormWrappedView(grok.View):
    grok.context(MammothApplication)
    grok.name('wrap')

    def render(self):
        form = MammothForm(self.context, self.request)
        form.template = grok.PageTemplateFile('bare_edit_form.pt')
        return """<html><body>%s</body></html>""" % form()

Once you have a form object, you can edit it's attributes. For example, change the template attribute to use a different template. Calling a form object itself will first update the form, setting up the widgets and processing data from the request, and then call and return the render() method. Howewver, the normal grok.View convention of first calling an a custom update() method if it exists to do any pre-processing is stil followed. If a URL redirect was generated during the update, it is allowed to happen without interruption and normal form processing doesn't take place.

Forms are grokked during start-up, which means like everything else they are registered with the Zope Component Architecture. That means that you can instantiate a Form object without needing to hard-code the class name in the calling View. This can be useful, since you can refactor your code and move or rename the Form class without needing to change the calling View code.

from zope import component
form = component.queryMultiAdapter(
    (self.context, self.request),
    name='index'
)
 

Form processing (post)

Posted by Adam Gr at Jun 19, 2009 05:31 AM
Form is being sent to parent view, so where and how should be this form processed? In view's update() method?