Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I need to add an entity reference filed to user entity programmatically. How this can be done? I checked the entity_reference_test.module and found following code snippet:
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
* Implements hook_entity_base_field_info().
*/
function entity_reference_test_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = array();
if ($entity_type->id() === 'entity_test') {
$fields['user_role'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('User role'))
->setDescription(t('The role of the associated user.'))
->setSetting('target_type', 'user_role')
->setSetting('handler', 'default');
}
return $fields;
}
But seems this does not work. Please help me to figure out this.
Any help will be highly appreciated.
Thanks in Advance.
Comments
Comment #3
jasn CreditAttribution: jasn as a volunteer commentedSorry I can't tell you why, but if you delete the entry "
->setSetting('handler', 'default')
" it should work for you.I have a similar problem, but in my case it is with the reference to a custom entity. The other field that I have uses a reference to an entity of the core and works perfectly without the handler.
Anyway, I advise you to enable it to be shown in the Field UI and you don't have it in your code. Tell me if you need to know how.
Comment #6
cilefen CreditAttribution: cilefen at Institute for Advanced Study commented