[Grok-dev] Recipe - How to create a vocabulary that allows the display of non-ASCII characters

Sebastian Ware sebastian at urbantalk.se
Mon Sep 24 08:01:47 EDT 2007


I just want to pitch my idea of what a recipe might look like. In  
this case showing how to create a vocabulary that displays unicode  
titles.

Mvh Sebastian

** Recipe - How to create a vocabulary that allows the display of non- 
ASCII characters **
Keywords: Recipe, Vocabulary, Unicode, Global Utility

How to create a vocabulary that displays non-ASCII titles. Useful for  
use with zope.schema.Choice fields. The title of each term that is to  
be displayed can be Unicode strings.

[code:vocabulary.py]
from zope import schema
from zope.schema.vocabulary import SimpleVocabulary
from hurry import query

class VocabularySource(object):
	
     def __call__(self, context):
	    # Get a list of objects (I am using hurry.query to search a  
catalog)
         theQuery = query.Eq(('workflow_catalog', 'workflow_state'),  
interfaces.PUBLISHED)
         result = query.query.Query().searchResults(theQuery)
         # For each object, add it as a list of terms  
(zope.schema.vocabulary.SimpleTerm)
         # creating each term with SimpleVocabulary.createTerm(value,  
token, title). This
         # allows the title to be unicode, the token has to be ASCII  
(and can be the
         # same as value).
         theTerms = []
         for item in result:
             theTerms.append(SimpleVocabulary.createTerm(item.__name__,
                                                         item.iso_code,
                                                         item.title))
         return  SimpleVocabulary(theTerms)

# Register the vocabulary as a global utility.
grok.global_utility(VocabularySource,
                     provides=schema.interfaces.IVocabularyFactory,
                     name=u'Published Objects')
[/code]

Now you can use this vocabulary as the source for a schema.Choice field.

   chosen_object = schema.Choice(title=u'The Object',  
vocabulary='Published Objects')

Or maybe with this more advanced list field with widget

   chosen_objects = schema.List(title=u'Selected Objects', unique=True,
                                value_type=schema.Choice 
(title=u'Objects',
                                                          
vocabulary='Published Objects'),
                                default=[])





More information about the Grok-dev mailing list