I'm trying to make an entity reference field a multi-select options select but I can't seem to find out how to make that happen. Any help is appreciated. Below is the code I'm using.

$fields['some_field'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Some Field'))
  ->setDescription(t('This is a field.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'other_entity')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 0,
    'settings' => [
      'options_select' => 'multiple',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(FALSE);
up vote 1 down vote accepted

Ultimately this was answered in a different but similar question I asked. The answer is the code below attached to the field in my entity.

use Drupal\Core\Field\FieldStorageDefinitionInterface;

->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) 

You can by using BaseFieldDefinition::setCardinality

Sets the maximum number of items allowed for the field.

By adding:

->setCardinality(0) 
// 0 means unlimited. Put 3 if you only want to allow up to 3 values

  • Thank you for the response. I added it to the entity but the form it still displays it as a drop down and not a multiple select list. I assume there is an setDisplayOptions option I need to apply to make this happen? After looking through the core code I couldn't seem to narrow that down. – themantimeforgot Dec 4 at 15:18
  • ->setCardinality(0) Didn't work for me or at least it didn't produce the outcome I was looking for. I asked a similar question but rather on the form display side of things and someone responded with the following similar answer that worked. ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) – themantimeforgot Dec 6 at 16:09
  • @themantimeforgot in the link I provided, I actually missed reading Possible values are positive integers or FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED.. In D7 zero was used for unlimited, but clearly no longer the case for D8. – No Sssweat Dec 7 at 2:06

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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