Autocomplete for TextLine that allows custom values

I'd like to give users autocomplete support for entering a city name while still allowing them to add cities not known to our system.

The training documentation has an example for a List that allows to select item from a vocabulary but this results in the property being a List.

list_field_voc_unconstrained = schema.List(
    title=u'List field with values from vocabulary but not constrained to them.',

Using the same approach on a TextLine with SelectFieldWidget results in a lookup error when rendering the form (SelectFieldWidget seems not to play well with TextLine):

        pattern_options={"placeholder": "select a city"},
    city = schema.TextLine(

zope.interface.interfaces.ComponentLookupError: ((<Container at /Plone/termine>, <WSGIRequest, URL=http://cms.localhost:8080/Plone/organisa/termine/++add++Event>, <plone.dexterity.browser.add.DefaultAddForm object at 0x7fbe98802e50>, <zope.schema._bootstrapfields.TextLine object at 0x7fbe990ee160>, <SelectWidget ''>), <InterfaceClass z3c.form.interfaces.ITerms>, '')

-> raise ComponentLookupError(objects, interface, name)

Using schema.Choice works but limits the user to the vocabulary values (as choice requires a vocabulary and does not have an option such as enforceVocabulary (from Products.AutocompleteWidget) that could be set to false)

        pattern_options={"placeholder": "select a city"},
    city = schema.Choice(

Is there a recommended way for a single select Textfield that allows custom input?

side question: does not mention GitHub - plone/plone.formwidget.autocomplete: z3c.form widget for Plone using jQuery Autocomplete. is this meant to be superseded by [Ajax]SelectWidget or is this still relevant and worth a try?

I think the subject field does exactly what you want to do: at master · plone/ · GitHub

thanks for your reply @tmassman. the pattern of the subject field is more or less simliar to list_field_voc_unconstrained from the example above.

drawback: it uses a schema.Tuple / schema.List field so the resulting attribute will be an iterable instead of str :frowning:

i also tried something like this in the meantime

  • form renders
  • widget allows vocab values and custom input
  • BUT widget is multiselect and i can't figure out how to stop it to allow mutiple values
  • i use a predefined vocab in the example below because i previously had troubles to get ajaxselectfield working with custom searchable vocabs / sources (errors similar to the ones reported in this thread)
        "maximumSelectionLength": 1,  # does not affect multiselect
        "multiple": False, # neither
city = schema.TextLine(

I was on the run yesterday, so sorry for my short reply.

I did this last year for a project and it works pretty well:

            'maximumSelectionSize': 1,
            'vocabularyUrl': get_ingredients_vocabulary_url,
    ingredient = schema.TextLine(

This looks exactly like your example above :thinking:

We use this in a DataGridField and the schema also includes a quantity and unit field, so people can add a list of ingredients, but one line can only have 1 selected ingredient. And if it does not exist before, it will be added to the vocabulary.

This runs on Plone 5.2.2 right now

Just for completeness, this is the vocabulary used:

  <!-- Dynamic incredients vocabulary. Used by the IRecipe content type. -->
from import KeywordsVocabulary
from zope.interface import implementer
from zope.schema.interfaces import IVocabularyFactory

class IngredientsVocabulary(KeywordsVocabulary):
    """Return a list of available ingredients."""

    keyword_index = 'recipeIngredients'

IngredientsVocabularyFactory = IngredientsVocabulary()

And the catalog definition:

  <!-- Index for IRecipe.ingredients. -->
  <index name="recipeIngredients" meta_type="KeywordIndex">
    <indexed_attr value="recipeIngredients" />

And the custom indexer:

def recipe_ingredients(obj):
    """Custom indexer for 'recipeIngredients' KeywordIndex."""
    result = set()
    ingredients = []
    ingredients.extend(obj.ingredients_details or [])

    # Check for sub recipes and index those ingredients as well
    sub_recipes = relapi.relations(obj, 'sub_recipe_links')
    for sub_recipe in sub_recipes:
        ingredients.extend(sub_recipe.ingredients_details or [])

    for ingredient in ingredients:
        name = ingredient.get('ingredient')
        if not name:
        if isinstance(name, tuple):
            for name_part in name:
    return tuple(result)
  <!-- Indexer: recipeIngredients for IRecipe. -->

Just a side note: recipes can have linked sub recipes, so you can use the recipe for e.g. dumplings for multiple main recipes. That’s what the sub_recipes above is for.


The code above uses a dynamic URL for the vocabulary. I think that was necessary because of the DataGridField. So just for completeness:

def get_ingredients_vocabulary_url(context):
    request = getRequest()
    ctx = request.PUBLISHED.context
    if not IRecipe.providedBy(ctx):
        ctx = plone.api.portal.get()
    return u'/'.join([
1 Like

Thank you for this! Until now, I never managed to make the AjaxSelectFieldWidget work in a DatagridField.

I have not seen this post before, this looks pretty cool.

Are you able to use the fields in a collection, too ( too see all 'items' that contain 'Apfel'?

Also; does this site have a reachable URL ?

If you configure it to be used for, yes:

  <!-- Recipe: Ingredients (List) -->
  <records interface=""
    <value key="title" i18n:translate="" i18n:domain="xxx">Rezept: Zutaten</value>
    <value key="description" i18n:translate="" i18n:domain="xxx"></value>
    <value key="enabled">True</value>
    <value key="sortable">False</value>
    <value key="operations">
    <value key="vocabulary">xxx.recipe_ingredients</value>
    <value key="group" i18n:translate="">Rezepte</value>

We use collective.collectionfilter and in the Zutaten widget you can see all the ingredients for all recipes.

1 Like

Replying to self: I spoke too soon.
Maybe we should split these last posts off to a new topic?

I do not see a noticeable difference when priming the select2 widget with the vocabulary url. Either with or without this, I see the following:
first row: ajaxselect does not trigger
second row: ajaxselect is being used

Edit to add: if I leave auto_append on in my DG field factory for the subform, and make the retourmenge field optional, then the select2 widget appears (without priming).

@adapter(schema.interfaces.IField, z3c.form.interfaces)
def ResultsDataGridFieldFactory(field, request):
    A special widget constructor setting up widget parameters for DGF.
    widget = DataGridFieldFactory(field, request)
    widget.allow_insert = False
    widget.allow_delete = False
    widget.allow_reorder = False
    #widget.auto_append = False
    return widget

Almost perfect, but for the unwanted "no value".

Plone Foundation Code of Conduct