1

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);

2 Answers 2

2

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) 
0

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

4
  • 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. Dec 4, 2018 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) Dec 6, 2018 at 16:09
  • 1
    @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, 2018 at 2:06
  • Ah ok, that makes a lot of sense. I appreciate the help, it definitely got me going in the right direction so it definitely helped. Dec 10, 2018 at 15:54

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.