drupal 8 BaseFieldDefinition entity_reference with condition

Viewed 1830

I am not sure if this is the right way to implement this, so I hope you can help me. I am trying to reference a custom content entity in Drupal 8 with the condition that only the entities created by the current user should show.

Basically CUSTOM ENTITY 1 -> CUSTOM ENTITY 2 (created by the user)

I found a way to do this with views, but I am wondering how to achieve this programmatically.

Please note that I have already managed to get a list of ids and display it as a drop down, but this is not what i want.

I would like to show the reference as autocomplete .

This is what i got so far:

$fields['dishes'] = BaseFieldDefinition::create('entity_reference')
        ->setLabel(t('Dishes'))
        ->setDescription(t('Select the dishes to add  to this menu'))
        ->setSetting('target_type', 'dish')
        ->setSetting('handler', 'default')
        ->setTranslatable(TRUE)
        ->setCardinality(-1)
        ->setDisplayOptions('view', [
            'label' => 'hidden',
            'type' => 'entity_reference_label',
            'weight' => -1,
        ])
        ->setDisplayOptions('form', [
            'type' => 'entity_reference_autocomplete',
            'weight' => -1,
            'settings' => [
                'match_operator' => 'CONTAINS',
                'size' => '60',
                'autocomplete_type' => 'tags',
                'placeholder' => '',
            ],
        ])
        ->setDisplayConfigurable('form', FALSE)
        ->setDisplayConfigurable('view', TRUE);

Is there a way to add conditions to this ? Or customise the query Drupal does to get the referenced entity?

1 Answers
Related