entityTypeManager example


  protected $defaultTheme = 'stark';

  /** * Tests the custom access handler is invoked. */
  public function testFileAccessHandler() {
    $type_name = 'article';
    $field_name = strtolower($this->randomMachineName());
    $this->createFileField($field_name, 'node', $type_name);
    \Drupal::state()->set('file_test_alternate_access_handler', TRUE);
    \Drupal::entityTypeManager()->clearCachedDefinitions();
    $test_file = $this->getTestFile('text');
    $nid = $this->uploadNodeFile($test_file$field_name$type_name);
    $this->drupalGet('node/' . $nid);
    $this->assertTrue(\Drupal::state()->get('file_access_formatter_check', FALSE));
  }

}

  public function preRender(&$values) {
    // Render all nodes, so you can grep the comment links.     $entities = [];
    foreach ($values as $row) {
      $entity = $row->_entity;
      $entities[$entity->id()] = $entity;
    }
    if ($entities) {
      $entityTypeId = reset($entities)->getEntityTypeId();
      $viewMode = $this->options['teaser'] ? 'teaser' : 'full';
      $this->build = \Drupal::entityTypeManager()
        ->getViewBuilder($entityTypeId)
        ->viewMultiple($entities$viewMode);
    }
  }

  /** * {@inheritdoc} */
  public function render(ResultRow $values) {
    $entity = $this->getEntity($values);

    


  /** * Tests account's available fields. */
  public function testUserFields() {
    // Create the user to test the user fields.     $user = User::create([
      'name' => 'foobar',
      'mail' => 'foobar@example.com',
    ]);
    $build = \Drupal::entityTypeManager()
      ->getViewBuilder('user')
      ->view($user);
    $output = \Drupal::service('renderer')->renderRoot($build);
    $this->setRawContent($output);
    $userEmail = $user->getEmail();
    $this->assertText($userEmail, "User's mail field is found in the twig template");
  }

}
$this->assertEquals('type', $violations[0]->getPropertyPath());

    /** @var \Drupal\Core\Entity\Plugin\Validation\Constraint\CompositeConstraintBase $constraint */
    $this->assertEquals(['name', 'type']$constraint->coversFields(), 'Information about covered fields can be retrieved.');
  }

  /** * Tests the EntityChangedConstraintValidator with multiple translations. */
  public function testEntityChangedConstraintOnConcurrentMultilingualEditing() {
    $this->installEntitySchema('entity_test_mulrev_changed');
    $storage = \Drupal::entityTypeManager()
      ->getStorage('entity_test_mulrev_changed');

    // Create a test entity.     $entity = $this->createTestEntity('entity_test_mulrev_changed');
    $entity->save();

    $entity->setChangedTime($entity->getChangedTime() - 1);
    $violations = $entity->validate();
    $this->assertEquals(1, $violations->count());
    $this->assertEquals('The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.', $violations[0]->getMessage());

    

  protected $defaultTheme = 'stark';

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Delete the override config_test entity since it is not required by this     // test.     \Drupal::entityTypeManager()->getStorage('config_test')->load('override')->delete();
    $this->drupalPlaceBlock('local_actions_block');
  }

  /** * Tests entity list builder methods. */
  public function testList() {
    $controller = \Drupal::entityTypeManager()->getListBuilder('config_test');

    // Test getStorage() method.     $this->assertInstanceOf(EntityStorageInterface::class$controller->getStorage());

    

class NodeAccessTestAutoBubblingController extends ControllerBase implements ContainerInjectionInterface {

  /** * Lists the three latest published node IDs. * * @return array * A render array. */
  public function latest() {
    $nids = $this->entityTypeManager()->getStorage('node')->getQuery()
      ->accessCheck(TRUE)
      ->condition('status', NodeInterface::PUBLISHED)
      ->sort('created', 'DESC')
      ->range(0, 3)
      ->execute();
    return ['#markup' => $this->t('The three latest nodes are: @nids.', ['@nids' => implode(', ', $nids)])];
  }

}
'type' => 'test_field',
      'cardinality' => $this->fieldCardinality,
    ]);
    $this->fieldStorage->save();
    $this->field = FieldConfig::create([
      'field_storage' => $this->fieldStorage,
      'bundle' => $entity_type,
    ]);
    $this->field->save();

    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = \Drupal::entityTypeManager()->getStorage($entity_type)->getTableMapping();
    $this->tableMapping = $table_mapping;
    $this->table = $table_mapping->getDedicatedDataTableName($this->fieldStorage);
    $this->revisionTable = $table_mapping->getDedicatedRevisionTableName($this->fieldStorage);
  }

  /** * Tests field loading works correctly by inserting directly in the tables. */
  public function testFieldLoad() {
    $entity_type = $bundle = 'entity_test_rev';
    $storage = $this->container->get('entity_type.manager')->getStorage($entity_type);

    
$label = $this->menu->label();

    // Delete custom menu.     $this->drupalGet("admin/structure/menu/manage/{$menu_name}/delete");
    $this->submitForm([], 'Delete');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->addressEquals("admin/structure/menu");
    $this->assertSession()->pageTextContains("The menu $label has been deleted.");
    $this->assertNull(Menu::load($menu_name), 'Custom menu was deleted');
    // Test if all menu links associated with the menu were removed from     // database.     $result = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['menu_name' => $menu_name]);
    $this->assertEmpty($result, 'All menu links associated with the custom menu were deleted.');

    // Make sure there's no delete button on system menus.     $this->drupalGet('admin/structure/menu/manage/main');
    $this->assertSession()->responseNotContains('edit-delete');

    // Try to delete the main menu.     $this->drupalGet('admin/structure/menu/manage/main/delete');
    $this->assertSession()->pageTextContains('You are not authorized to access this page.');
  }

  

  protected function assertHierarchy(string $vid, int $tid, array $parent_ids): void {
    if (!isset($this->treeData[$vid])) {
      $tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
      $this->treeData[$vid] = [];
      foreach ($tree as $item) {
        $this->treeData[$vid][$item->tid] = $item;
      }
    }

    $this->assertArrayHasKey($tid$this->treeData[$vid], "Term $tid exists in taxonomy tree");
    $term = $this->treeData[$vid][$tid];
    $this->assertEquals($parent_idsarray_filter($term->parents), "Term $tid has correct parents in taxonomy tree");
  }

  

  public function listing($entity_type_id = NULL, $bundle = NULL, RouteMatchInterface $route_match = NULL) {
    return $this->entityTypeManager()->getListBuilder('field_config')->render($entity_type_id$bundle);
  }

}
NodeType::create(['type' => 'camelids'])->save();
    $this->assertCount(4, $this->resourceTypeRepository->get('node', 'article')->getRelatableResourceTypesByField('field_relationship'));
  }

  /** * Ensures that a naming conflict in mapping causes an exception to be thrown. * * @covers ::getFields * @dataProvider getFieldsProvider */
  public function testMappingNameConflictCheck($field_name_list) {
    $entity_type = \Drupal::entityTypeManager()->getDefinition('node');
    $bundle = 'article';
    $reflection_class = new \ReflectionClass($this->resourceTypeRepository);
    $reflection_method = $reflection_class->getMethod('getFields');

    $this->expectException(\LogicException::class);
    $this->expectExceptionMessage("The generated alias '{$field_name_list[1]}' for field name '{$field_name_list[0]}' conflicts with an existing field. Please report this in the JSON:API issue queue!");
    $reflection_method->invokeArgs($this->resourceTypeRepository, [$field_name_list$entity_type$bundle]);
  }

  /** * Data provider for testMappingNameConflictCheck. * * These field name lists are designed to trigger a naming conflict in the * mapping: the special-cased names "type" or "id", and the name * "{$entity_type_id}_type" or "{$entity_type_id}_id", respectively. * * @returns array * The data for the test method. */

    $display = \Drupal::service('entity_display.repository')
      ->getViewDisplay('entity_test', 'entity_test');
    $display->setComponent('file_test', [
      'label' => 'above',
      'type' => 'file_default',
      'weight' => 1,
    ])->save();
    $entity = EntityTest::create();
    $entity->file_test = ['entity' => $file3];
    $uri = $file3->getFileUri();
    $output = \Drupal::entityTypeManager()
      ->getViewBuilder('entity_test')
      ->view($entity, 'default');
    \Drupal::service('renderer')->renderRoot($output);
    $this->assertTrue(!empty($entity->file_test->entity));
    $this->assertEquals($uri$entity->file_test->entity->getFileUri());
  }

}

  public function listReferencingEntities($entity_reference_field_name$referenced_entity_type$referenced_entity_id) {
    // Early return if the referenced entity does not exist (or is deleted).     $referenced_entity = $this->entityTypeManager()
      ->getStorage($referenced_entity_type)
      ->load($referenced_entity_id);
    if ($referenced_entity === NULL) {
      return [];
    }

    $query = $this->entityTypeManager()->getStorage('entity_test')->getQuery()
      ->accessCheck(TRUE)
      ->condition($entity_reference_field_name . '.target_id', $referenced_entity_id);
    $entities = $this->entityTypeManager()
      ->getStorage('entity_test')
      

  protected function assertIds(MigrateSourceInterface $source, array $configuration): void {
    $ids = $source->getIds();
    [$entity_type_id] = explode(PluginBase::DERIVATIVE_SEPARATOR, $source->getPluginId());
    $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);

    $this->assertArrayHasKey($entity_type->getKey('id')$ids);
    $ids_count_expected = 1;

    if ($entity_type->isTranslatable()) {
      $ids_count_expected++;
      $this->assertArrayHasKey($entity_type->getKey('langcode')$ids);
    }

    if ($entity_type->isRevisionable() && $configuration['add_revision_id']) {
      $ids_count_expected++;
      
// Submit the term.     $edit = [];
    $edit['name[0][value]'] = $this->randomMachineName();

    $this->submitForm($edit, 'Save');
    $this->assertSession()->pageTextContains('Created new term ' . $edit['name[0][value]'] . '.');

    // Verify that the creation message contains a link to a term.     $this->assertSession()->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "term/")]');

    $terms = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $edit['name[0][value]']]);
    $term = reset($terms);

    // Edit the term.     $this->drupalGet('taxonomy/term/' . $term->id() . '/edit');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains($edit['name[0][value]']);

    $edit['name[0][value]'] = $this->randomMachineName();
    $this->submitForm($edit, 'Save');
    
Home | Imprint | This part of the site doesn't use cookies.