def test_only_titled_if_triples(self): from zope.schema.interfaces import ITitledTokenizedTerm no_titles = self.tree_vocab_2() for term in no_titles: self.assertIsNone(term.title) self.assertFalse(ITitledTokenizedTerm.providedBy(term)) all_titles = self.tree_vocab_3() for term in all_titles: self.assertIsNotNone(term.title) self.assertTrue(ITitledTokenizedTerm.providedBy(term))
def minimums(self): if self.terms is None: # update() has not been called yet return () items = [] selected = self.minimum # items.append({ # 'id': self.id + '-novalue', # 'value': '--MINVALUE--', # 'content': u"Min", # 'selected': selected is None or selected == 0, # }) for count, term in enumerate(self.terms): if term.token == '--MAXVALUE--': continue id = '{0}-{1:d}'.format(self.id, count) content = term.title or term.value if ITitledTokenizedTerm.providedBy(term): content = translate( term.title, context=self.request, default=term.title) items.append({ 'id': id, 'value': term.token, 'content': content, 'selected': term.token == selected}) return items
def update(self): """See z3c.form.interfaces.IWidget. We do everything the radio widget's update methode does, but we also put the entrytype into the items dictionary.""" super(EntryTypeWidget, self).update() addFieldClass(self) self.items = [] for count, term in enumerate(self.terms): checked = self.isChecked(term) id = '%s-%i' % (self.id, count) label = term.token if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) if interfaces.IBiblatexEntryType.providedBy(term): _type = term else: _type = zope.component.getUtility(interface.IBiblatexEntryType, name=term.token, context=getSite()) self.items.append({ 'id': id, 'name': self.name + ':list', 'value': term.token, 'label': label, 'checked': checked, 'entrytype': _type })
def get_item(self, term, count=0): """Get item matching given term""" item_id = '%s-%i' % (self.id, count) content = term.value if ITitledTokenizedTerm.providedBy(term): content = self.request.localizer.translate(term.title) return {'id': item_id, 'value': term.token, 'content': content}
def cmp(self, term, query): # ajax search widget does a search on this vocabulary, # if we have titled terms, we have to compare against the title # otherwise use the value. if ITitledTokenizedTerm.providedBy(term): return query in term.title.lower() return query in term.value.lower()
def test_get_term_by_token(self): # we can get a term by its token source = RedisAutocompleteSource( host=self.redis_host, port=self.redis_port, zset_name="autocomplete-foo") result = source.getTermByToken(u'1') self.assertTrue(ITitledTokenizedTerm.providedBy(result))
def test_ctor_defaults(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne('VALUE') self.assertEqual(term.value, 'VALUE') self.assertEqual(term.token, 'VALUE') self.assertEqual(term.title, None) self.assertFalse(ITitledTokenizedTerm.providedBy(term))
def items(self): items = [] if self.terms is not None: # update() has been called if ((not self.required or self.prompt) and not bool(self.multiple)): message = self.noValueMessage if self.prompt: message = self.promptMessage items.append({ 'id': self.id + '-novalue', 'value': self.noValueToken, 'content': message, 'selected': self.value == [] }) for count, term in enumerate(self.terms): selected = self.isSelected(term) id = '%s-%i' % (self.id, count) content = term.token if ITitledTokenizedTerm.providedBy(term): content = translate( term.title, context=self.request, default=term.title) items.append( {'id':id, 'value':term.token, 'content':content, 'selected':selected}) return items
def displayValue(self): registry = getUtility(IRegistry) urls = registry.get(self.links_record) value = [] for token in self.value: # Ignore no value entries. They are in the request only. if token == self.noValueToken: continue try: term = self.terms.getTermByToken(token) except LookupError: # silently ignore missing tokens, because INPUT_MODE and # HIDDEN_MODE does that too continue title = term.value if ITitledTokenizedTerm.providedBy(term): title = translate(term.title, context=self.request, default=term.title) value.append({ 'term': title, 'url': urls.get(term.value).get('url'), 'class': 'sdg-{}'.format(token) }) return value
def users(self): context = self.context memtool = getToolByName(context, 'portal_membership') vocabulary = queryUtility(schema.interfaces.IVocabularyFactory, name='ftw.notification.base.users', context=context) if vocabulary: users = vocabulary(context) finalized = [] for t in users: userid = t.value member = memtool.getMemberById(userid) if member is None: continue title = t.title if ITitledTokenizedTerm.providedBy(t) else t.value user = dict(title=title, value=t.value, email=member.getProperty("email", ""), selected=t.value in self.pre_select) finalized.append(user) finalized.sort(key=lambda user: user['title'].lower()) return finalized
def updateItems(self): """ taken from z3c.form.browser.checkbox (radio), but description and query_description added.""" self.items = [] for count, term in enumerate(self.terms): checked = self.isChecked(term) id = '%s-%i' % (self.id, count) label = term.token if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) self.items.append({ 'id': id, 'name': self.name + ':list', 'value': term.token, 'label': label, 'checked': checked, 'description': term.value.description, 'query_description': term.value.query_description, })
def test_ctor_explicit(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne('TERM', 'TOKEN', 'TITLE') self.assertEqual(term.value, 'TERM') self.assertEqual(term.token, 'TOKEN') self.assertEqual(term.title, 'TITLE') self.assertTrue(ITitledTokenizedTerm.providedBy(term))
def items(self): # TODO: check if we should cache the return list if self.terms is None: # update() not yet called return () vocab = getUtility( IVocabularyFactory, "org.bccvl.site.algorithm_category_vocab")(self.context) items = OrderedDict((cat.value, []) for cat in chain((SimpleTerm(None),), vocab)) for count, term in enumerate(self.terms): alg = term.brain.getObject() # skip algorithm without category # if alg.algorithm_category is None or alg.algorithm_category not in items: # continue itemList = items[alg.algorithm_category] checked = self.isChecked(term) id = '%s-%i' % (self.id, count) if ITitledTokenizedTerm.providedBy(term): label = translate( term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) catterm = SimpleTerm(None) if alg.algorithm_category in vocab: catterm = vocab.getTerm(alg.algorithm_category) itemList.append({'id': id, 'name': self.name + ':list', 'value': term.token, 'label': label, 'checked': checked, 'subject': term.brain.Subject, 'description': term.brain.Description, 'category': catterm, 'pos': len(itemList)}) return items.values()
def items(self): if self.terms is None: return () registry = getUtility(IRegistry) urls = registry.get(self.links_record) items = [] for term in self.terms: checked = self.isChecked(term) id = '%s-%s' % (self.id, term.value) if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) items.append({ 'id': id, 'name': self.name + ':list', 'value': term.token, 'label': label, 'checked': checked, 'url': urls.get(term.value).get('url') }) return items
def __call__(self): term = self.context token = term.token title = term.title if ITitledTokenizedTerm.providedBy(term) else token if isinstance(title, six.binary_type): title = title.decode("UTF-8") return {"token": token, "title": translate(title, context=self.request)}
def test_iter(self): # we can iterate over all elements source = RedisAutocompleteSource( host=self.redis_host, port=self.redis_port, zset_name="autocomplete-foo") elem_list = [x for x in source] self.assertEqual(len(elem_list), 4) self.assertTrue(ITitledTokenizedTerm.providedBy(elem_list[0]))
def __call__(self, vocabulary_id): term = self.context token = term.token title = term.title if ITitledTokenizedTerm.providedBy(term) else token return { '@id': '{}/{}'.format(vocabulary_id, token), 'token': token, 'title': title }
def getTermTitleByToken(field, token): try: term = field.vocabulary.getTermByToken(str(token)) except LookupError: return token if ITitledTokenizedTerm.providedBy(term): return term.title else: return term.value
def render_default_title(self, item, value): """Render the default title colum with the term's title.""" term = self.terms.getTerm(item) if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) return label
def test_get_term_contained(self): # we can get contained terms as ITerm source = RedisSource(host=self.redis_host, port=self.redis_port) term = source.getTerm(u'foo') assert ITitledTokenizedTerm.providedBy(term) self.assertTrue(hasattr(term, 'value')) self.assertEqual(term.value, u'foo') self.assertTrue(hasattr(term, 'token')) self.assertEqual(term.token, 'Zm9v') self.assertTrue(hasattr(term, 'title')) self.assertEqual(term.title, u'bar')
def addItem(idx, group, term, prefix=''): selected = self.isSelected(term) if selected: ignored.remove(term.token) id = '%s-%s%i' % (self.id, prefix, idx) content = term.token if ITitledTokenizedTerm.providedBy(term): content = translate( term.title, context=self.request, default=term.title) optgroups[group].append( {'id': id, 'value': term.token, 'content': content, 'selected': selected})
def test_get_term_contained(self): # we can get contained terms as ITerm source = RedisAutocompleteSource( host=self.redis_host, port=self.redis_port, zset_name="autocomplete-foo") term = source.getTerm(u'4') assert ITitledTokenizedTerm.providedBy(term) self.assertTrue(hasattr(term, 'value')) self.assertEqual(term.value, u'4') self.assertTrue(hasattr(term, 'token')) self.assertEqual(term.token, u'4') self.assertTrue(hasattr(term, 'title')) self.assertEqual(term.title, u'Bär (4)')
def render_default_title(self, item, value): """Render the default title colum with the term's title.""" if isinstance(item, NullObject): return _(u'label_none', default=u'None') term = self.terms.getTerm(item) if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) return label
def textForValue(self, term): """Extract a string from the `term`. The `term` must be a vocabulary tokenized term. This can be overridden to support more complex `term` objects. The token is returned here since it's the only thing known to be a string, or str()able. """ if ITitledTokenizedTerm.providedBy(term): return self.translate(term.title) return term.token
def items(self): if self.terms is None: # update() has not been called yet return () items = [] if self.multiple is None: message = self.noValueMessage if self.prompt: message = self.promptMessage items.append({ 'id': self.id + '-novalue', 'value': self.noValueToken, 'content': message, 'selected': self.value == [] }) unordered_items = {} optgroups = [] for count, term in enumerate(self.terms): # Exctract optgroups in an ordered list, so we can use this to # preserve the main order of optgroups. if not term.optgroup in optgroups: optgroups.append(term.optgroup) selected = self.isSelected(term) id = '%s-%i' % (self.id, count) content = term.title if ITitledTokenizedTerm.providedBy(term): content = self.getContent(term) if not term.optgroup in unordered_items: unordered_items[term.optgroup] = [] unordered_items[term.optgroup].append({ 'id': id, 'value': term.token, 'content': content, 'selected': selected, }) for group in optgroups: if not group: for ding in unordered_items[group]: items.append({ 'id': ding['id'], 'value': ding['value'], 'content': ding['content'], 'selected': ding['value'] == [] }) else: item = {} item['title'] = group item['member'] = unordered_items[group] items.append(item) self.getSize(items) return items
def textForValue(self, term): """Extract a string from the `term`. The `term` must be a vocabulary tokenized term. This can be overridden to support more complex `term` objects. The token is returned here since it's the only thing known to be a string, or str()able. """ titled = ITitledTokenizedTerm(term, None) if titled is None: return term.token return self.translate(titled.title)
def _overrideValue(self, widget, value): if value: widget.value = ['selected'] widget.items = [] for count, term in enumerate(widget.terms): checked = widget.isChecked(term) id = '%s-%i' % (widget.id, count) label = term.token if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=widget.request, default=term.title) widget.items.append({'id': id, 'name': widget.name + ':list', 'value': term.token, 'label': label, 'checked': checked})
def add_item(idx, term, prefix=''): selected = self.is_selected(term) if selected and term.token in ignored: ignored.remove(term.token) item_id = '%s-%s%i' % (self.id, prefix, idx) content = term.token if ITitledTokenizedTerm.providedBy(term): content = self.request.localizer.translate(term.title) items.append({ 'id': item_id, 'value': term.token, 'content': content, 'selected': selected })
def displayValue(self): value = {} for token in self.value: # Ignore no value entries. They are in the request only. if token == self.noValueToken: continue term = self.terms.getTermByToken(token) if ITitledTokenizedTerm.providedBy(term): content = self.getContent(term) else: value.append(term.value) if not term.optgroup in value: value[term.optgroup] = [] value[term.optgroup].append(content) return value
def items(self): # TODO: check if we should cache the return list if self.terms is None: # update() not yet called return () items = [] for count, term in enumerate(self.terms): checked = self.isChecked(term) id = '%s-%i' % (self.id, count) if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) items.append ({'id': id, 'name': self.name + ':list', 'value':term.token, 'label':label, 'checked': checked, 'subject': term.brain.Subject}) return items
def test_fromItems_triples(self): from zope.interface import Interface from zope.schema.interfaces import ITitledTokenizedTerm class IStupid(Interface): pass ITEMS = [('one', 1, 'title 1'), ('two', 2, 'title 2'), ('three', 3, 'title 3'), ('fore!', 4, 'title four')] vocabulary = self._getTargetClass().fromItems(ITEMS) self.assertEqual(len(vocabulary), len(ITEMS)) for item, term in zip(ITEMS, vocabulary): self.assertTrue(ITitledTokenizedTerm.providedBy(term)) self.assertEqual(term.token, item[0]) self.assertEqual(term.value, item[1]) self.assertEqual(term.title, item[2]) for item in ITEMS: self.assertIn(item[1], vocabulary)
def items(self): """Items list getter""" if self.terms is None: return for count, term in enumerate(self.terms): checked = self.is_checked(term) item_id = '%s-%i' % (self.id, count) if ITitledTokenizedTerm.providedBy(term): translate = self.request.localizer.translate label = translate(term.title) else: label = to_unicode(term.value) yield { 'id': item_id, 'name': self.name, 'value': term.token, 'label': label, 'checked': checked }
def display_value(self): """Widget display value""" value = [] for token in self.value: # Ignore no value entries. They are in the request only. if token == self.no_value_token: continue try: term = self.terms.getTermByToken(token) except LookupError: # silently ignore missing tokens, because INPUT_MODE and # HIDDEN_MODE does that too continue if ITitledTokenizedTerm.providedBy(term): translate = self.request.localizer.translate value.append(translate(term.title)) else: value.append(term.value) return value
def _overrideValue(self, widget, value): if value: widget.value = ['selected'] widget.items = [] for count, term in enumerate(widget.terms): checked = widget.isChecked(term) id = '%s-%i' % (widget.id, count) label = term.token if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=widget.request, default=term.title) widget.items.append({ 'id': id, 'name': widget.name + ':list', 'value': term.token, 'label': label, 'checked': checked })
def items(self): if self.terms is None: # update() has not been called yet return () items = [] if self.multiple is None: message = self.noValueMessage if self.prompt: message = self.promptMessage items.append({ 'id': self.id + '-novalue', 'value': self.noValueToken, 'content': message, 'selected': self.value == [] }) unordered_items = {} optgroups = [] for count, term in enumerate(self.terms): # Exctract optgroups in an ordered list, so we can use this to # preserve the main order of optgroups. if not term.optgroup in optgroups: optgroups.append(term.optgroup) selected = self.isSelected(term) id = '%s-%i' % (self.id, count) content = term.title if ITitledTokenizedTerm.providedBy(term): content = self.getContent(term) if not term.optgroup in unordered_items: unordered_items[term.optgroup] = [] unordered_items[term.optgroup].append({ 'id': id, 'value': term.token, 'content': content, 'selected': selected, }) for group in optgroups: item = {} item['title'] = group item['member'] = unordered_items[group] items.append(item) self.getSize(items) return items
def items(self): if self.terms is None: # update() has not been called yet return () items = [] if self.multiple is None: message = self.noValueMessage if self.prompt: message = self.promptMessage items.append( { "id": self.id + "-novalue", "value": self.noValueToken, "content": message, "selected": self.value == [], } ) unordered_items = {} optgroups = [] for count, term in enumerate(self.terms): # Exctract optgroups in an ordered list, so we can use this to # preserve the main order of optgroups. if not term.optgroup in optgroups: optgroups.append(term.optgroup) selected = self.isSelected(term) id = "%s-%i" % (self.id, count) content = term.title if ITitledTokenizedTerm.providedBy(term): content = self.getContent(term) if not term.optgroup in unordered_items: unordered_items[term.optgroup] = [] unordered_items[term.optgroup].append( {"id": id, "value": term.token, "content": content, "selected": selected} ) for group in optgroups: item = {} item["title"] = group item["member"] = unordered_items[group] items.append(item) self.getSize(items) return items
def update(self): super(RadioWidget, self).update() widget.addFieldClass(self) if getattr(self.field, 'horizontal', False): self.klass = 'z-hlisting' self.items = [] #if not self.required : # message = self.noValueMessage # self.items.append({ # 'id': self.id + '-novalue', # 'value': self.noValueToken, # 'content': message, # 'selected': self.value == [] # }) for count, term in enumerate(self.terms): selected = self.isSelected(term) id = '%s-%i' % (self.id, count) content = term.token if ITitledTokenizedTerm.providedBy(term): content = translate( term.title, context=self.request, default=term.title) item = TermItem(id, term.value, term.token, term.title or unicode(term.value), content, selected, getattr(term, 'description', u'')) context = getattr(self.form, 'context', None) view = queryMultiAdapter( (context, self.form, self, item, self.request), IPagelet, term.token) if view is None: view = getMultiAdapter( (context, self.form, self, item, self.request), IPagelet) view.update() self.items.append(view)
def items(self): # TODO: check if we should cache the return list if self.terms is None: # update() not yet called return () vocab = getUtility(IVocabularyFactory, "org.bccvl.site.algorithm_category_vocab")( self.context) items = OrderedDict( (cat.value, []) for cat in chain((SimpleTerm(None), ), vocab)) for count, term in enumerate(self.terms): alg = term.brain.getObject() # skip algorithm without category # if alg.algorithm_category is None or alg.algorithm_category not in items: # continue itemList = items[alg.algorithm_category] checked = self.isChecked(term) id = '%s-%i' % (self.id, count) if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) catterm = SimpleTerm(None) if alg.algorithm_category in vocab: catterm = vocab.getTerm(alg.algorithm_category) itemList.append({ 'id': id, 'name': self.name + ':list', 'value': term.token, 'label': label, 'checked': checked, 'subject': term.brain.Subject, 'description': term.brain.Description, 'category': catterm, 'pos': len(itemList) }) return items.values()
def items(self): # TODO: check if we should cache the return list if self.terms is None: # update() not yet called return () items = [] for count, term in enumerate(self.terms): checked = self.isChecked(term) id = '%s-%i' % (self.id, count) if ITitledTokenizedTerm.providedBy(term): label = translate(term.title, context=self.request, default=term.title) else: label = util.toUnicode(term.value) items.append({ 'id': id, 'name': self.name + ':list', 'value': term.token, 'label': label, 'checked': checked, 'subject': term.brain.Subject }) return items
def textForValue(self, term): """Extract a string from the `term`. The `term` must be a vocabulary tokenized term. """ if ITitledTokenizedTerm.providedBy(term): if '-' in term.value: code, territory = term.value.split('-') territory = territory.upper() result = self.languages.get(code, None) # If we don't have a translation for the language, return the # English one and don't bother with the country name if result is None or result == code: return term.title territory = self.territories.get(territory, territory) result = "%s (%s)" % (result, territory) else: result = self.languages.get(term.value, None) # If we don't have a translation for the language, return the # default English text, rather than the language code if result is None or result == term.value: return term.title return result return term.token
def test_bytes_non_ascii_value(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne(b'Snowman \xe2\x98\x83') self.assertEqual(term.value, b'Snowman \xe2\x98\x83') self.assertEqual(term.token, 'Snowman \\xe2\\x98\\x83') self.assertFalse(ITitledTokenizedTerm.providedBy(term))
def test_unicode_non_ascii_value(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne(u'Snowman \u2603') self.assertEqual(term.value, u'Snowman \u2603') self.assertEqual(term.token, 'Snowman \\u2603') self.assertFalse(ITitledTokenizedTerm.providedBy(term))
def test_bytes_value(self): from zope.schema.interfaces import ITitledTokenizedTerm term = self._makeOne(b'term') self.assertEqual(term.value, b'term') self.assertEqual(term.token, 'term') self.assertFalse(ITitledTokenizedTerm.providedBy(term))
def test_iter(self): # we can iterate over all elements source = RedisSource(host=self.redis_host, port=self.redis_port) elem_list = [x for x in source] self.assertEqual(len(elem_list), 1) self.assertTrue(ITitledTokenizedTerm.providedBy(elem_list[0]))
def test_get_term_by_token(self): # we can get a term by its token source = RedisSource(host=self.redis_host, port=self.redis_port) token = tokenize("foo") result = source.getTermByToken(token) self.assertTrue(ITitledTokenizedTerm.providedBy(result))