- Drupal CMS Developer
- Website speed optimisation
- Drupal 6 to Drupal 8 migrations
Drupal 8 custom entity entity_reference field filtered by role in select box
I have a custom entity, I want to create an entity form, within that entity I have an entity_reference field which references users. I want the field to be a select box, but I don't want to display all users on the Drupal 8 site, instead I only want to show users with a specific role. You can actually do this via the base field definition in the entity, you don't have to create a view like everyone suggests nor override classes, its actually quite easy when you know how...
<?php
$fields['sales_manager_id'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t("Sales manager ID"))
->setSetting('target_type', 'user')
->setSetting('handler_settings', [
'filter' => [
'type' => 'role',
'role' => 'sales_manager',
],
])
->setDescription(t("Sales representative"))
->setDisplayOptions('view', [
'label' => 'above',
'type' => 'entity_reference',
'weight' => -5,
])
->setDisplayOptions('form', [
'type' => 'options_select',
])
->setDisplayConfigurable('view', TRUE)
->setDisplayConfigurable('form', FALSE)
->setTranslatable(FALSE)
->setRequired(TRUE);
?>
- Scripts: