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

Version: 8.0.0-beta7 » 8.0.x-dev

Core issues are now filed against the dev versions where changes will be made. Document the specific release you are using in your issue comment. More information about choosing a version.

Version: 8.0.x-dev » 8.9.x-dev

Drupal 8.8.7 was released on June 3, 2020 and is the final full bugfix release for the Drupal 8.8.x series. Branches prior to 8.8.x are not supported, and Drupal 8.8.x will not receive any further development aside from security fixes. Sites should prepare to update to Drupal 8.9.0 or Drupal 9.0.0 for ongoing support.

Bug reports should be targeted against the 8.9.x-dev branch from now on, and new development or disruptive changes should be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

jasn’s picture

Sorry 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.

Version: 8.9.x-dev » 9.2.x-dev

Drupal 8 is end-of-life as of November 17, 2021. There will not be further changes made to Drupal 8. Bugfixes are now made to the 9.3.x and higher branches only. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.2.x-dev » 9.3.x-dev
cilefen’s picture

Status: Active » Closed (outdated)