How to Display Vocabulary Title in Archetypes?
-
28-04-2021 - |
Question
I want my custom type to display the stored vocabulary's title. The field definition looks like:
atapi.LinesField(
'member_field',
searchable=1,
index='KeywordIndex',
multiValued=1,
storage=atapi.AnnotationStorage(),
vocabulary_factory='member_name',
widget=AutocompleteWidget(
label=_(u"Member Name"),
description=_(u"Multiple Lines, One Per Line."),
actb_timeout=-1,
actb_expand_onfocus=0,
actb_filter_bogus=0,
),
enforceVocabulary=0,
),
The vocabulary definition looks like:
class member_name(object):
implements(IVocabularyFactory)
def __call__(self, context=None):
items = (
SimpleTerm(value='john', title=u'John Doe'),
SimpleTerm(value='paul', title=u'Paul Smith'),
... ...
)
return SimpleVocabulary(items)
member_nameFactory = member_name()
The corresponding page template looks like:
<div tal:define="mbrs context/member_field|nothing"
tal:condition="mbrs">
Member List:
<span tal:repeat="mbr mbrs">
<span tal:replace="mbr">Member Name</span>
<span class="separator"
tal:condition="not: repeat/mbr/end" tal:replace="string:, " />
</span>
</div>
The example result, showing only values, looks like: Member List: paul , john
. How can I display their titles instead, like: Member List: Paul Smith , John Doe
?
La solution
Vocabularies (in Zope3 style) are just named utilities and you can retrieve them like this:
from zope.component import getUtility
from zope.schema.interfaces import IVocabularyFactory
factory = getUtility(IVocabularyFactory, vocabularyname)
vocabulary = factory(self.context)
and then you can get the term's title like this:
fieldvalue = self.context.getField('myfield').get(self.context)
term = vocabulary.getTerm(fieldvalue)
print "Term value is %s token is %s and title is %s" + (term.value, term.token, term.title)
More info:
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow