I've got a custom entity ('content_sharing') and defined one of the fields as $fields['entity_definition'] = BaseFieldDefinition::create('string').... The create-form I'm showing the user is loaded with an empty entity via a controller like so:

    $contentSharing = $this->entityTypeManager()
    $form = $this->entityTypeManager()
      ->getFormObject('content_sharing', 'custom_mode')
    $output['form'] = $this->formBuilder()->getForm($form);

What I need now is to present the user a select-list of possible strings (options) that are dynamically pre-populated everytime the form is loaded. The only FieldWidget for string fields is a textfield. I tried to come up with my own custom FieldWidget similar to this

 * @FieldWidget(
 *   id = "string_select_list",
 *   module = "content_sharing",
 *   label = @Translation("Select list for strings"),
 *   field_types = {
 *     "string"
 *   },
 *  multiple_values = FALSE
 * )

class StringSelectList extends OptionsWidgetBase {

However, this resulted in an error and I noticed that this needs to have options defined which I cannot (don't know how to) provide for my string basefield.

I could of cource just add a dummy form-element select list that provides the values for my entity field, but I wanted to use the entityform as it is without any further custom elements.

Possible with a custom widget or any other solutions?

1 Answer 1


Create a list_string base field and use as widget OptionsSelectWidget.

$fields['entity_definition'] = BaseFieldDefinition::create('list_string')
  ->setLabel(t('Entity Definition'))
    'allowed_values' => [
      'value1' => 'Value 1',
      'value2' => 'Value 2',
  ->setDisplayOptions('form', [
    'type' => 'options_select',

To update the options dynamically add a callback to the base field settings allowed_values_function, see How do I programmatically update the allowed values of a list field?

  • I thought about that too, but was hesitant because of having to update the allowed values every time. I'll give that a try.
    – theuni
    Mar 4, 2019 at 18:25
  • I guess that passing an argument other than FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity is impossible...? Just asking since the options of one of the fields depends on the selected value of another form-field.
    – theuni
    Mar 4, 2019 at 18:57
  • Found a way. I'm calculating all possible allowed values in allowed_values_function, then getting those values inside my buildForm() via $options = options_allowed_values($fields['field_id']);and creating a subset of those, dependent on another form fields selected value. Works well. Thanks!
    – theuni
    Mar 5, 2019 at 6:45

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.