createEntityReferenceField example

protected static $modules = ['entity_reference_test', 'entity_test_update'];

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->installEntitySchema('entity_test_rev');

    // Create a field.     $this->createEntityReferenceField(
      $this->entityType,
      $this->bundle,
      $this->fieldName,
      'Field test',
      $this->referencedEntityType,
      'default',
      ['target_bundles' => [$this->bundle]],
      FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
    );

  }

  
// Create a comment type.     CommentType::create([
      'id' => 'comment',
      'label' => 'Default comments',
      'description' => 'Default comment field',
      'target_entity_type_id' => 'node',
    ])->save();

    // Add comment and entity reference comment fields.     $this->addDefaultCommentField('node', 'page', 'comment');
    $this->createEntityReferenceField(
      'node',
      'page',
      'entity_reference_comment',
      'Entity Reference Comment',
      'comment',
      'default',
      ['target_bundles' => ['comment']]
    );

    $comment_admin_user = $this->drupalCreateUser([
      'skip comment approval',
      
$this->drupalLogin($web_user);
  }

  /** * Tests the entity reference field with all its supported field widgets. */
  public function testSupportedEntityTypesAndWidgets() {
    foreach ($this->getTestEntities() as $key => $referenced_entities) {
      $this->fieldName = 'field_test_' . $referenced_entities[0]->getEntityTypeId();

      // Create an Entity reference field.       $this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, $this->fieldName, $referenced_entities[0]->getEntityTypeId(), 'default', [], 2);

      /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
      $display_repository = \Drupal::service('entity_display.repository');

      // Test the default 'entity_reference_autocomplete' widget.       $display_repository->getFormDisplay($this->entityType, $this->bundle)
        ->setComponent($this->fieldName)
        ->save();

      $entity_name = $this->randomMachineName();
      $edit = [
        
$edit = [
      'new_storage_type' => 'entity_reference',
      'label' => 'Test Field',
      'field_name' => 'test_reference_field',
    ];
    $this->submitForm($edit, 'Save and continue');
    $this->assertSession()->optionNotExists('settings[target_type]', 'entity_test_no_id');

    // Trying to do it programmatically should raise an exception.     $this->expectException('\Drupal\Core\Field\FieldException');
    $this->expectExceptionMessage('Entity type "entity_test_no_id" has no ID key and cannot be targeted by entity reference field "test_reference_field"');
    $this->createEntityReferenceField('node', $node_type, 'test_reference_field', 'Test Field', 'entity_test_no_id');
  }

}
$this->installEntitySchema('user');
  }

  /** * @covers ::getDefinitions */
  public function testGetDefinitions() {
    // Create an entity reference field to make sure that migrations derived by     // EntityReferenceTranslationDeriver do not get discovered without     // migrate_drupal enabled.     $this->createEntityReferenceField('user', 'user', 'field_entity_reference', 'Entity Reference', 'node');

    // Make sure retrieving all the core migration plugins does not throw any     // errors.     $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions();
    // All the plugins provided by core depend on migrate_drupal.     $this->assertEmpty($migration_plugins);

    // Enable a module that provides migrations that do not depend on     // migrate_drupal.     $this->enableModules(['migrate_external_translated_test']);
    $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions();
    
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Create an entity bundle that has a media reference field.     $entity_test_bundle = EntityTestBundle::create([
      'id' => $this->testEntityBundleId,
    ]);
    $entity_test_bundle->save();
    $this->createEntityReferenceField(
      $this->testEntityTypeId,
      $this->testEntityBundleId,
      $this->mediaFieldName,
      $this->mediaFieldName,
      'media'
    );
  }

  /** * Tests the settings summary. * * @param array $settings * The settings to use for the formatter. * @param array $expected_summary * The expected settings summary. * * @covers ::settingsSummary * * @dataProvider providerTestSettingsSummary */

  protected $comment;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->createEntityReferenceField(
      'node',
      'article',
      'entity_reference_comment',
      'Entity Reference Comment',
      'comment',
      'default',
      ['target_bundles' => ['comment']]
    );
    \Drupal::service('entity_display.repository')
      ->getFormDisplay('node', 'article')
      ->setComponent('entity_reference_comment', ['type' => 'options_select'])
      
// Use Stark theme for testing markup output.     \Drupal::service('theme_installer')->install(['stark']);
    $this->config('system.theme')->set('default', 'stark')->save();
    $this->installEntitySchema('entity_test');
    // Grant the 'view test entity' permission.     $this->installConfig(['user']);
    Role::load(RoleInterface::ANONYMOUS_ID)
      ->grantPermission('view test entity')
      ->save();

    $this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);

    // Set up a field, so that the entity that'll be referenced bubbles up a     // cache tag when rendering it entirely.     FieldStorageConfig::create([
      'field_name' => 'body',
      'entity_type' => $this->entityType,
      'type' => 'text',
      'settings' => [],
    ])->save();
    FieldConfig::create([
      'entity_type' => $this->entityType,
      
$vocabulary->save();

    // Second, create the field.     entity_test_create_bundle('test_bundle');
    $this->fieldName = strtolower($this->randomMachineName());
    $handler_settings = [
      'target_bundles' => [
        $vocabulary->id() => $vocabulary->id(),
      ],
      'auto_create' => TRUE,
    ];
    $this->createEntityReferenceField('entity_test', 'test_bundle', $this->fieldName, NULL, 'taxonomy_term', 'default', $handler_settings);

    // Create two terms and also two accounts.     for ($i = 0; $i <= 1; $i++) {
      $term = Term::create([
        'name' => $this->randomMachineName(),
        'vid' => $vocabulary->id(),
      ]);
      $term->save();
      $this->terms[] = $term;
      $this->accounts[] = $this->createUser();
    }
    
// Create a vocabulary.     $vocabulary = Vocabulary::create([
      'name' => $this->vocabulary,
      'description' => $this->vocabulary,
      'vid' => $this->vocabulary,
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
    ]);
    $vocabulary->save();

    // Create a term reference field on node.     $this->createEntityReferenceField(
      'node',
      $this->bundle,
      $this->fieldName,
      'Term reference',
      'taxonomy_term',
      'default',
      ['target_bundles' => [$this->vocabulary]],
      FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
    );

    // Create a term reference field on user.
->save();
    $type = NodeType::create([
      'type' => 'article',
    ]);
    $type->save();
    $this->user = User::create([
      'name' => 'user1',
      'mail' => 'user@localhost',
      'status' => 1,
      'roles' => ['test_role_one', 'test_role_two'],
    ]);
    $this->createEntityReferenceField('node', 'article', 'field_relationships', 'Relationship', 'node', 'default', ['target_bundles' => ['article']], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $this->user->save();

    $this->node = Node::create([
      'title' => 'dummy_title',
      'type' => 'article',
      'uid' => $this->user->id(),
      'uuid' => static::$nodeUuid[1],
    ]);
    $this->node->save();

    $this->node2 = Node::create([
      
// Create two content types, with one content type containing a field that     // references entities of the second content type.     $this->createContentType([
      'type' => 'bundle_with_reference_field',
      'name' => 'bundle_with_reference_field',
    ]);
    $this->createContentType([
      'type' => 'bundle_referenced',
      'name' => 'bundle_referenced',
    ]);

    $this->createEntityReferenceField('node', 'bundle_with_reference_field', 'field_reference', 'Reference field', 'node', 'default', [
      'target_bundles' => ['bundle_referenced'],
    ]);

    // Enable layout builder to the content type with the reference field, and     // add the reference field to the layout builder display.     $this->container->get('entity_display.repository')
      ->getViewDisplay('node', 'bundle_with_reference_field', 'full')
      ->enableLayoutBuilder()
      ->setComponent('field_reference', ['type' => 'entity_reference_label'])
      ->save();
  }

  
'bypass node access',
    ]));
    $this->vocabulary = $this->createVocabulary();
    $this->fieldName = 'taxonomy_' . $this->vocabulary->id();

    $handler_settings = [
      'target_bundles' => [
        $this->vocabulary->id() => $this->vocabulary->id(),
      ],
      'auto_create' => TRUE,
    ];
    $this->createEntityReferenceField('node', 'article', $this->fieldName, NULL, 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);

    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('node', 'article')
      ->setComponent($this->fieldName, [
        'type' => 'options_select',
      ])
      ->save();
    $display_repository->getViewDisplay('node', 'article')
      ->setComponent($this->fieldName, [
        'type' => 'entity_reference_label',
      ])
// Create a vocabulary and add two term reference fields to article nodes.     $this->vocabulary = $this->createVocabulary();

    $this->fieldName1 = mb_strtolower($this->randomMachineName());
    $handler_settings = [
      'target_bundles' => [
        $this->vocabulary->id() => $this->vocabulary->id(),
      ],
      'auto_create' => TRUE,
    ];
    $this->createEntityReferenceField('node', 'article', $this->fieldName1, NULL, 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);

    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('node', 'article')
      ->setComponent($this->fieldName1, [
        'type' => 'options_select',
      ])
      ->save();
    $display_repository->getViewDisplay('node', 'article')
      ->setComponent($this->fieldName1, [
        'type' => 'entity_reference_label',
      ])
/** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');
    $cache_contexts_manager = \Drupal::service("cache_contexts_manager");

    // Force a request via GET so we can get     // \Drupal::service('renderer')->render() cache working.     $request = \Drupal::request();
    $request_method = $request->server->get('REQUEST_METHOD');
    $request->setMethod('GET');

    // Create an entity reference field and an entity that will be referenced.     $this->createEntityReferenceField('entity_test', 'entity_test', 'reference_field', 'Reference', 'entity_test');
    \Drupal::service('entity_display.repository')
      ->getViewDisplay('entity_test', 'entity_test', 'full')
      ->setComponent('reference_field', [
        'type' => 'entity_reference_entity_view',
        'settings' => ['link' => FALSE],
      ])->save();
    $entity_test_reference = $this->createTestEntity('entity_test');
    $entity_test_reference->save();

    // Get a fully built entity view render array for the referenced entity.     $build = $this->container->get('entity_type.manager')->getViewBuilder('entity_test')->view($entity_test_reference, 'full');
    
Home | Imprint | This part of the site doesn't use cookies.