I'm creating a custom entity type, that has the following base field (defined in a class that extends ContentEntityBase)

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields['recipient_id'] = BaseFieldDefinition::create('entity_reference')
    ->setDescription(t('The recipient(s)'))
    ->setSetting('target_type', 'user')
    ->setSetting('handler', 'default')
    ->setDisplayOptions('view', array(
      'label' => 'above',
      'type' => 'entity_reference_label',
      'weight' => -3,
    ->setDisplayOptions('form', array(
      'type' => 'entity_reference_autocomplete',
      'settings' => array(
        'match_operator' => 'CONTAINS',
        'size' => 60,
        'autocomplete_type' => 'tags',
        'placeholder' => '',
      'weight' => -3,
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

I've set the field to have unlimited cardinality. I'm trying to create the getters and setters for this field, however I'm not finding any examples of entity types with multiple values.

I need to create the following getters and setters:

// Add a single recipient to the entity
public function setRecipient()
// retrieve all recipients for the entity
public function getRecipients()

Does anyone have an example of how to set up these functions to work with a multiple value field?

1 Answer 1

// Add a single recipient to the entity
public function setRecipient()

What now, add or set? If it is adding to the existing list, I'd recommend to name it addRecipient().

I'd also recommend to name the field recipients or so, to indicate that it has multiple values.

You can add an item to a field item list with \Drupal\Core\TypedData\ListInterface::appendItem(), for example $this->get('recipient_id')->appendItem($recipient_entity_or_id_or_value_array)

To get all referenced entities, there is a referencedEntities() method on entity reference field item lists, or you can use a loop.

  • Thanks berdir, much appreciated. I'm using the referencedEntities() method, but you said 'or you can use a loop' - what would you loop through?
    – Jaypan
    Commented Apr 7, 2017 at 11:10
  • 1
    same as with all fields, foreach ($this->get('recipient_id') as $item) { $item->entity }
    – Berdir
    Commented Apr 7, 2017 at 13:15

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.