WARNING
This example doesn't actually work for me. For some reason, the RemoteForm is acting like a regular html form, serving up a new page instead of performing the replacements we're looking for. I'll update this page as soon as I figure out why this is happening.
Overview
RemoteForm and it's companion widget, LinkRemoteFunction?, provide an ajaxian method of presenting a form. RemoteForm's purpose is to provide HTML's form functionality without forcing a page refresh.
Basic RemoteForm Usage
In this example, we're going to demo a form using TextField?, CheckBox?, and a Radio button. To start, in the controller, start by creating a class that contains the fields you want to display:
from turbogears.widgets.base import WidgetsList
from turbogears.widgets import TextField, CheckBox, RadioButtonList
import turbogears as tg
class SearchFormFields(WidgetsList):
name = TextField()
age = TextField()
check = CheckBox()
radio = RadioButtonList(options=[(1, "Python"),
(2, "Java"),
(3, "Pascal"),
(4, "Ruby")],
default=4)
Then, expose a controller function to create the remote form upon request:
class DemoController(identity.SecureResource):
""" Demonstrate the use of RemoteForm. """
@tg.expose(template="templates.remoteformdemo")
def index(self):
item_searchform = RemoteForm(
name="ItemSearch",
fields=SearchFormFields(),
submit_text="Search")
return dict(item_searchform=item_searchform)
The last controller function is a call-back, which is used by the widget to retrieve the data inside it's asynchronous request.
@tg.expose(format = "json")
def do_search(self, **kw):
""" Echo the parameters back, json formatted. """
return """Received data:<br />%r""" % kw
Finally, in the template, call the widget's display function. You can pass parameters to display() to customize the effects. The example below displays "Searching..." during the XMLHttpRequest, and "Done!" when it completes.
<span py:replace="item_searchform.display(
action='/do_search',
target_dom='items',
before='getElement(\'loading\').innerHTML=\'Searching...\';',
on_complete='getElement(\'loading\').innerHTML=\'Done!\';',
confirm='Are you sure you want to submit this request?'
)">
</span>
<div name="loading"></div>
<div name="items"></div>
And that's it. Browsers hitting our demo page will be served up some nice RemoteForm goodness.
Note: Most of the above was gleaned from the widget example in the toolbox. See the demo there for a live example.