I wanted to have a field on an SQLFORM that behaved like IS_IN_DB
(i.e. a drop box with values shown to the user and a corresponding id
inserted into the database).

I didn't want to take the source data from the database though because
it is more program data than user data and I wanted to use
internationalisation.

I made this validator. I'm no Python expert so maybe there is a better
way. I include it as a meagre offering in case it's helpful and for
comments and improvements.

class IS_IN_DATASET(object):
    """
    Like IS_IN_DB but gets its data from code not the database, so can
do internationalisation etc.

    e.g. given
    testSet = { 'fields': [ 'storeVal', 'name' ],
               'rows' : [[0, T('Alpha')], [1, T('Beta')], [2, T
('Gamma')]]}

    can have something like
    db.table.myField.requires=IS_IN_DATASET
(testSet,'storeVal',label='name')

    renders as a drop-box like IS_IN_DB
    """
    def __init__(self,dbset,forDb,label=None,error_message='value not
in data set!'):
        forDb=str(forDb)
        if not label:
          label='%%(%s)s' % forDb

        self.forDbPos = dbset['fields'].index(forDb) if forDb in dbset
['fields'] else 0
        self.forUserPos = dbset['fields'].index(label) if label in
dbset['fields'] else 0
        mulog.debug("forDbPos is " + str(self.forDbPos) + " for user "
+ str(self.forUserPos))
        self.error_message=error_message
        self.theset=None
        # theset is a list of the values that are put in the record
        # labels is what is shown to the user
        self.theset=[ str(r[self.forDbPos]) for r in dbset['rows'] ]
        self.labels=[ r[self.forUserPos] for r in dbset['rows']]

    def options(self):
       return [(k,self.labels[i]) for i,k in enumerate(self.theset)]

    def __call__(self,value):
       if value in self.theset:
          return(value, None)
       return (value,self.error_message)



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"web2py Web Framework" 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/web2py?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to