I have a field which normally expects a value selected from a managed list (e.g. a list of courses, a list of colleges). The client would like the visitor to be prompted with one of the managed list as they type in their entry, to promote consistency in spelling, etc., but not to restrict the value with this UI. In other words, it should allow any text entry.

So that means, I think I want a plain text field with an implementation of the select2 widget that doesn't require the entry of one of the select options.

Note that this isn't the same as the classic select-or-other where you have a select field followed by a hidden text field that becomes visible when other is selected, and in some ways seems like it should be easier.

This kind of UI is natively supported by the select2 widget

Any clues on implementation?

1 Answer 1


Assuming you are storing these as civi option values, you could do it the way civi does it with the wrench icon to add new options on-the-fly. There's a data-option you add to the wrench tag.

If you prefer it more like the contact entity refs with the "New" options, you can almost do it with addEntityRef, but it would need to support the "create" option in props, e.g. $form->addEntityRef('gender_id', 'Gender', ['entity' => 'OptionValue', 'create' => TRUE, 'api' => ['params' => ['option_group_id' => 3]]]); (the "create" doesn't work there). But you might be able to civix generate your own entity, and make that work. You want to validate it server-side, so it's not just a matter of setting the select2 "tags" option. (I'm sure you've seen the "an illegal choice has been detected" message in drupal.)

  • I think it has to be an option group. If it was an entity reference, a new entry would spawn a new entity, which seems dangerous and messy.
    – Alan Dixon
    Mar 27 at 15:19
  • I think the answer I thought I was looking for is in here: stackoverflow.com/questions/31199507/… i.e. the "tags" option for select2 requires a text input field, so with a little custom js, I can just apply the select2 to my text field and somehow tell it to use my option group as the option list.
    – Alan Dixon
    Mar 27 at 15:21
  • re: your last sentence - in fact, that's exactly the challenge, I don't want server-side validation, I want the user to be allowed to put anything in the box, I just want to encourage them to re-use an existing value (or rather, one of a curated list of values).
    – Alan Dixon
    Mar 27 at 15:24
  • In this case the "entity" is OptionValue. But I see you're saying you don't want visitors to be allowed to add values to the suggestion list.
    – Demerit
    Mar 27 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.