Long ago, Matthew Bevan wrote:
I wrote and submitted to the docs.turbogears.org server the following:

http://docs.turbogears.org/1.0/UnifiedControllers

It describes in full detail (with source code) how to combine form/ action controllers without any of problems associated with just @exposing and @validating the entire thing. The code described also has the added benefit of allowing validation of forms built at execution time.

The gist of it is:

class MyController(Controller):
     @expose(template="project.templates.genericform")
     def index(self, **kw):
         form = MyForm(fields=MyFields())

         if kw:
             @validate(form=form)
             def get_errors(self, tg_errors=None, **data):
                 return tg_errors, data

             tg_errors, data = get_errors(self, **kw)
[...]

I like it. Really. The two methods way has always been a pet peeve of mines.

But I don't want to copy-and-paste the inner function a few hundred of
times, so I extracted it, _and_ abused tg_errors:

def get_errors(self, form, **kw):
   @validate(form=form)
   def valid(self, tg_errors=None, **kw):
       return tg_errors, kw
   if not kw:
       return {'xxx':'This message should not be displayed. Not an
error, really. The form is empty yet.'}, kw
   return valid(self, **kw)


So, this is my controller for adding a user while validating the data:

   @expose(template='erp.templates.users.add')
   def add(self, **kw):
       form = UserAddForm.form
       tg_errors, data = get_errors(self, form, **kw)

       if not tg_errors:
           user = User.new(**data)
           tg.flash("User '%s' has been created" % user.uid)
           raise tg.redirect('/users/view', uid=user.uid))

       return dict(form=form)

(User.new checks for duplicates and the like)



Seems to work, with default field values too, and... I have a unified
controller/error_handler that is shorter and simpler than the two
functions pattern.
Now, since I am not well-versed in decorator intricacies and magic, I
hope it won't explode on me, or break with python 2.5.

Too easy, is it?

I'm still looking for a nice way to avoid spurious "please insert a
value" when passing some default by GET method. uhm.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to