Search code examples
plonedexterity

non required SelectFieldWidget


I have a dexterity content type and I'd like to have a Select-Field which is not required and which values came from a vocabulary.

This is the vocabulary:

@grok.provider(IContextSourceBinder)
def voc_test(context):
    values = range(10, 21)
    terms = map(lambda x: SimpleTerm(value=str(x),
                                 title=str(x)), values)
    return SimpleVocabulary(terms)

And this the definition of the field:

from plone.directives import dexterity, form
from plone.namedfile.field import NamedImage
from zope import schema


class IMyType(form.Schema):     
    ... 
    form.widget('test', SelectFieldWidget)
    test = schema.List(
        title=_(u"Test"),
        value_type=schema.Choice(source=vocabularies.voc_test),
        description=_(u"desc_test"),
        required=False,
     )

What I get is a select field with my values from the vocabulary and the first value is 'No Value'. That is fine. But when I hit save and have 'No Value' selected a error message is shown:

Traceback (innermost last):

Module ZPublisher.Publish, line 138, in publish
Module ZPublisher.mapply, line 77, in mapply
Module ZPublisher.Publish, line 48, in call_object
Module plone.z3cform.layout, line 66, in __call__
Module plone.z3cform.layout, line 50, in update
Module plone.dexterity.browser.edit, line 52, in update
Module plone.z3cform.fieldsets.extensible, line 59, in update
Module plone.z3cform.patch, line 30, in GroupForm_update
Module z3c.form.group, line 145, in update
Module plone.app.z3cform.csrf, line 21, in execute
Module z3c.form.action, line 98, in execute
Module z3c.form.button, line 315, in __call__
Module z3c.form.button, line 170, in __call__
Module plone.dexterity.browser.edit, line 23, in handleApply
Module z3c.form.group, line 98, in extractData
Module z3c.form.form, line 147, in extractData
Module z3c.form.field, line 303, in extract
Module z3c.form.converter, line 316, in toFieldValue
Module z3c.form.term, line 41, in getValue
Module z3c.form.term, line 38, in getTermByToken
Module zope.schema.vocabulary, line 133, in getTermByToken
LookupError: --NOVALUE--

If I change:

required=False, 

to

required=True

saving works.

Hopefully someone can help. Thanks.


Solution

  • Set a default that is within your vocabulary and make the field required so that "--NOVALUE--" is not in the options.

    If, for some reason, you want to use "-- NOVALUE --" for that default, then add it to the vocabulary. If the field is set required, it will not be duplicated.