Order SimpleVocabulary Terms..?

Hi peeps, I need help trying to sort something out. At the moment I create a dynamic vocabulary where terms are added intermittently, is there a way to order a SimpleVocabulary..? I can't find any documentation which suggests this is possible...

Any help would be greatly appreciated! Thanks :slight_smile:

I sort my Items in the Vocabulary like so:

# vocabulary.py
def createTerms(context, items):
    portal = api.portal.get()
    terms = []
    for item in items:
        msgid = _(item)        
        translated = portal.translate(msgid)        
        simpleTerm = SimpleTerm(item, token=idnormalizer.normalize(item), title=translated)
        terms.append(simpleTerm)
    return SimpleVocabulary(terms)

def institutes(context):
    """
    create a Vocabulary from a List of Institutes
    the list lives in the configuration registry
    """
    items = api.portal.get_registry_record('mf.institutes')
    items = sorted(items)
    return createTerms(context, items)
<!--configure.zcml-->
<configure
    xmlns="http://namespaces.zope.org/zope"
    xmlns:five="http://namespaces.zope.org/five"
    xmlns:genericsetup="http://namespaces.zope.org/genericsetup">
    
    <utility
        name="mf.institutes"
        component=".vocabulary.institutes"
        provides="zope.schema.interfaces.IVocabularyFactory" />
         
</configure>
# interfaces.py
class ISupervisor(model.Schema):
    
    institute = schema.Choice(
        title = _(u"Institute"),
        required = True,
        missing_value='',
        vocabulary=u"mf.institutes"
    )

    directives.widget(
        'institute',
        AjaxSelectFieldWidget,
        vocabulary='mf.institutes'
    )
2 Likes

At most places where you typically use a "vocabulary" , you can instead use a "vocabulary factory", i.e. a function which returs a vocabulary (the function must provide a specific interface). This factory can order the terms as needed and then wrap the ordered term list into a vocabulary.

1 Like