[Zope3-Users] "Smarter" values for values = [] in Choice schema fields?

Marius Gedminas marius at gedmin.as
Thu Nov 6 11:30:27 EST 2008


On Thu, Nov 06, 2008 at 02:13:56PM +0100, Hermann Himmelbauer wrote:
> I quite often have Choice schema fields in my applications. In many cases, 
> these choice fields should have fixed values, thus I do it like this:
> 
> color = Choice( title=u"Color", values=['red', 'green', 'yellow'])
> 
> My application then uses the these values for further processing, e.g.:
> 
> if color == 'red': stop_traffic()
> 
> The problem is, that often it is more appropriate to have one value for 
> display, and another for internal processing (e.g. when msgid strings are 
> involved, when the program needs specific values etc.)
> 
> The only way I found is to set up a vocabulary and use 
> SimpleVocabulary.createTerm(key, n, name), however, that's quite tedious, as 
> I need to write quite some code, register the vocabulary etc.

Not really.

> So, perhaps there's a simpler solution? I'd favour something like this:
> 
> color = Choice(titel=u"Color", values = [('red', 0, u"Red"), ('green', 1, 
> u"Green")....])
> 
> Is that possible?

Define a helper function

def vocabulary(*terms):
    return SimpleVocabulary([SimpleTerm(value, token, title)
                             for value, token, title in terms])

and use it

    color = Choice(title=u"Color",
                   vocabulary=vocabulary(
                       (0, 'red', u'Red'),
                       (1, 'green', u'Green'),
                       ))

HTH,
Marius Gedminas
-- 
Undergraduates owe their happiness chiefly to the fact that they are no
longer at school...The nonsense which was knocked out of them at school is
all gently put back at Oxford or Cambridge
	        -- Sir Max Beerbohm (1872-1956)
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.zope.org/pipermail/zope3-users/attachments/20081106/4d66b718/attachment.bin 


More information about the Zope3-users mailing list