bundle example

$book_links = $this->bookOutlineStorage->loadMultiple($nids);
      // Load nodes with proper translation.       $nodes = $this->entityTypeManager->getStorage('node')->loadMultiple($nids);
      $nodes = array_map([$this->entityRepository, 'getTranslationFromContext']$nodes);
      // @todo Sort by weight and translated title.       // @todo use route name for links, not system path.       foreach ($book_links as $link) {
        $nid = $link['nid'];
        if (isset($nodes[$nid]) && $nodes[$nid]->access('view')) {
          $link['url'] = $nodes[$nid]->toUrl();
          $link['title'] = $nodes[$nid]->label();
          $link['type'] = $nodes[$nid]->bundle();
          $this->books[$link['bid']] = $link;
        }
      }
    }
  }

  /** * {@inheritdoc} */
  public function getLinkDefaults($nid) {
    return [
      

  public function overview(RouteMatchInterface $route_match$entity_type_id = NULL) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $route_match->getParameter($entity_type_id);
    $account = $this->currentUser();
    $handler = $this->entityTypeManager()->getHandler($entity_type_id, 'translation');
    $manager = $this->manager;
    $entity_type = $entity->getEntityType();
    $use_latest_revisions = $entity_type->isRevisionable() && ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id$entity->bundle());

    // Start collecting the cacheability metadata, starting with the entity and     // later merge in the access result cacheability metadata.     $cacheability = CacheableMetadata::createFromObject($entity);

    $languages = $this->languageManager()->getLanguages();
    $original = $entity->getUntranslated()->language()->getId();
    $translations = $entity->getTranslationLanguages();
    $field_ui = $this->moduleHandler()->moduleExists('field_ui') && $account->hasPermission('administer ' . $entity_type_id . ' fields');

    $rows = [];
    
if ($nids) {
      $vids = array_filter($this->options['vids']);
      if (empty($this->options['limit'])) {
        $vids = [];
      }
      $result = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getNodeTerms($nids$vids);

      foreach ($result as $node_nid => $data) {
        foreach ($data as $tid => $term) {
          $this->items[$node_nid][$tid]['name'] = \Drupal::service('entity.repository')->getTranslationFromContext($term)->label();
          $this->items[$node_nid][$tid]['tid'] = $tid;
          $this->items[$node_nid][$tid]['vocabulary_vid'] = $term->bundle();
          $this->items[$node_nid][$tid]['vocabulary'] = $vocabularies[$term->bundle()]->label();

          if (!empty($this->options['link_to_taxonomy'])) {
            $this->items[$node_nid][$tid]['make_link'] = TRUE;
            $this->items[$node_nid][$tid]['path'] = 'taxonomy/term/' . $tid;
          }
        }
      }
    }
  }

  
/** * Tests that link normalization cache information is not lost. * * @see https://www.drupal.org/project/drupal/issues/3077287 */
  public function testLinkNormalizationCacheability() {
    $user = User::create([
      'name' => $this->randomMachineName(),
      'pass' => $this->randomString(),
    ]);
    $user->save();
    $resource_type = $this->resourceTypeRepository->get($user->getEntityTypeId()$user->bundle());
    $resource_object = ResourceObject::createFromEntity($resource_type$user);
    $cache_tag_to_invalidate = 'link_normalization';
    $normalized_links = $this->serializer
      ->normalize($resource_object->getLinks(), 'api_json')
      ->withCacheableDependency((new CacheableMetadata())->addCacheTags([$cache_tag_to_invalidate]));
    assert($normalized_links instanceof CacheableNormalization);
    $normalization_parts = [
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE => [
        'type' => CacheableNormalization::permanent($resource_object->getTypeName()),
        'id' => CacheableNormalization::permanent($resource_object->getId()),
        'links' => $normalized_links,
      ],
public function getRevisionId() {
    return $this->getEntityKey('revision');
  }

  /** * {@inheritdoc} */
  public function isTranslatable() {
    // Check the bundle is translatable, the entity has a language defined, and     // the site has more than one language.     $bundles = $this->entityTypeBundleInfo()->getBundleInfo($this->entityTypeId);
    return !empty($bundles[$this->bundle()]['translatable']) && !$this->getUntranslated()->language()->isLocked() && $this->languageManager()->isMultilingual();
  }

  /** * {@inheritdoc} */
  public function preSave(EntityStorageInterface $storage) {
    // An entity requiring validation should not be saved if it has not been     // actually validated.     assert(!$this->validationRequired || $this->validated, 'Entity validation was skipped.');

    $this->validated = FALSE;

    
$result = AccessResult::allowed();

    $entity_type_id = $entity->getEntityTypeId();
    $result->addCacheableDependency($entity);
    // Add the cache dependencies used by     // ContentTranslationManager::isPendingRevisionSupportEnabled().     if (\Drupal::moduleHandler()->moduleExists('content_moderation')) {
      foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
        $result->addCacheableDependency($workflow);
      }
    }
    if (!ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id$entity->bundle())) {
      return $result;
    }

    if ($entity->isDefaultTranslation()) {
      return $result;
    }

    $config = ContentLanguageSettings::load($entity_type_id . '.' . $entity->bundle());
    $result->addCacheableDependency($config);
    if (!$this->contentTranslationManager->isEnabled($entity_type_id$entity->bundle())) {
      return $result;
    }
    FieldStorageConfig::create([
      'field_name' => static::$fieldName,
      'type' => 'datetime',
      'entity_type' => static::$entityTypeId,
      'settings' => ['datetime_type' => DateTimeItem::DATETIME_TYPE_DATETIME],
    ])
      ->save();

    FieldConfig::create([
      'field_name' => static::$fieldName,
      'entity_type' => static::$entityTypeId,
      'bundle' => $this->entity->bundle(),
      'settings' => ['default_value' => static::$dateString],
    ])
      ->save();

    // Reload entity so that it has the new field.     $this->entity = $this->entityStorage->load($this->entity->id());
    $this->entity->set(static::$fieldName['value' => static::$dateString]);
    $this->entity->save();
  }

  /** * {@inheritdoc} */

  protected function assertEntity(int $id, string $expected_language, string $expected_label, string $expected_vid, string $expected_description = '', string $expected_format = NULL, int $expected_weight = 0, array $expected_parents = [], int $expected_field_integer_value = NULL, int $expected_term_reference_tid = NULL): void {
    /** @var \Drupal\taxonomy\TermInterface $entity */
    $entity = Term::load($id);
    $this->assertInstanceOf(TermInterface::class$entity);
    $this->assertSame($expected_language$entity->language()->getId());
    $this->assertSame($expected_label$entity->label());
    $this->assertSame($expected_vid$entity->bundle());
    $this->assertSame($expected_description$entity->getDescription());
    $this->assertSame($expected_format$entity->getFormat());
    $this->assertSame($expected_weight$entity->getWeight());
    $this->assertHierarchy($expected_vid$id$expected_parents);
  }

  /** * Assert that a term is present in the tree storage, with the right parents. * * @param string $vid * Vocabulary ID. * @param int $tid * ID of the term to check. * @param array $parent_ids * The expected parent term IDs. * * @internal */
// Add access-protected field.       FieldStorageConfig::create([
        'entity_type' => static::$entityTypeId,
        'field_name' => 'field_rest_test',
        'type' => 'text',
      ])
        ->setCardinality(1)
        ->save();
      FieldConfig::create([
        'entity_type' => static::$entityTypeId,
        'field_name' => 'field_rest_test',
        'bundle' => $this->entity->bundle(),
      ])
        ->setLabel('Test field')
        ->setTranslatable(FALSE)
        ->save();

      // Add multi-value field.       FieldStorageConfig::create([
        'entity_type' => static::$entityTypeId,
        'field_name' => 'field_rest_test_multivalue',
        'type' => 'string',
      ])
        
// Reset the index.     $this->index = NULL;
    // Reset history.     $this->history = [];
  }

  /** * {@inheritdoc} */
  public function checkNodeType(NodeInterface $node) {
    // Fetch information about the forum field.     $field_definitions = $this->entityFieldManager->getFieldDefinitions('node', $node->bundle());
    return !empty($field_definitions['taxonomy_forums']);
  }

  /** * {@inheritdoc} */
  public function unreadTopics($term$uid) {
    $query = $this->connection->select('node_field_data', 'n');
    $query->join('forum', 'f', '[n].[vid] = [f].[vid] AND [f].[tid] = :tid', [':tid' => $term]);
    $query->leftJoin('history', 'h', '[n].[nid] = [h].[nid] AND [h].[uid] = :uid', [':uid' => $uid]);
    $query->addExpression('COUNT([n].[nid])', 'count');
    

class TermForm extends ContentEntityForm {

  /** * {@inheritdoc} */
  public function form(array $form, FormStateInterface $form_state) {
    $term = $this->entity;
    $vocab_storage = $this->entityTypeManager->getStorage('taxonomy_vocabulary');
    /** @var \Drupal\taxonomy\TermStorageInterface $taxonomy_storage */
    $taxonomy_storage = $this->entityTypeManager->getStorage('taxonomy_term');
    $vocabulary = $vocab_storage->load($term->bundle());

    $parent = $this->getParentIds($term);
    $form_state->set(['taxonomy', 'parent']$parent);
    $form_state->set(['taxonomy', 'vocabulary']$vocabulary);

    $form['relations'] = [
      '#type' => 'details',
      '#title' => $this->t('Relations'),
      '#open' => $taxonomy_storage->getVocabularyHierarchyType($vocabulary->id()) == VocabularyInterface::HIERARCHY_MULTIPLE,
      '#weight' => 10,
    ];

    

function callback_allowed_values_function(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {
  if (isset($entity) && ($entity->bundle() == 'not_a_programmer')) {
    $values = [
      1 => 'One',
      2 => 'Two',
    ];
  }
  else {
    $values = [
      'Group 1' => [
        0 => 'Zero',
        1 => 'One',
      ],
      
$this->assertFalse($storage->hasData());

    // Verify default properties on a newly created empty entity.     $empty = EntityTestLabel::create();
    $this->assertNull($empty->id->value);
    $this->assertNull($empty->name->value);
    $this->assertNotEmpty($empty->uuid->value);
    $this->assertSame($default_langcode$empty->langcode->value);

    // Verify ConfigEntity properties/methods on the newly created empty entity.     $this->assertTrue($empty->isNew());
    $this->assertSame('entity_test_label', $empty->bundle());
    $this->assertNull($empty->id());
    $this->assertNotEmpty($empty->uuid());
    $this->assertNull($empty->label());

    // Verify Entity properties/methods on the newly created empty entity.     $this->assertSame('entity_test_label', $empty->getEntityTypeId());
    // The URI can only be checked after saving.     try {
      $empty->toUrl();
      $this->fail('EntityMalformedException was thrown.');
    }
    
$this->assertEquals(1, $entity->postCreateCount);
    // Verify that none of the other methods have been invoked.     $this->assertEquals(0, EntityTestBundleClass::$preDeleteCount);
    $this->assertEquals(0, EntityTestBundleClass::$postDeleteCount);
    $this->assertEquals(0, EntityTestBundleClass::$postLoadCount);
    $this->assertCount(0, EntityTestBundleClass::$postLoadEntitiesCount);

    // Verify statically created entity with bundle class returns correct     // bundle.     $entity = EntityTestBundleClass::create(['type' => 'custom']);
    $this->assertInstanceOf(EntityTestBundleClass::class$entity);
    $this->assertEquals('bundle_class', $entity->bundle());

    // We should have seen preCreate() a 2nd time.     $this->assertEquals(2, EntityTestBundleClass::$preCreateCount);
    // postCreate() is specific to each entity instance, so still 1.     $this->assertEquals(1, $entity->postCreateCount);
    // Verify that none of the other methods have been invoked.     $this->assertEquals(0, EntityTestBundleClass::$preDeleteCount);
    $this->assertEquals(0, EntityTestBundleClass::$postDeleteCount);
    $this->assertEquals(0, EntityTestBundleClass::$postLoadCount);
    $this->assertCount(0, EntityTestBundleClass::$postLoadEntitiesCount);

    
$this->assertContains('config_test:entity4', $dependent_ids, 'config_test.dynamic.entity4 has a dependency on config_test module.');
    $this->assertContains('config_query_test:entity1', $dependent_ids, 'config_test.query.entity1 has a dependency on config_test module.');
    $this->assertContains('config_query_test:entity2', $dependent_ids, 'config_test.query.entity2 has a dependency on config_test module.');

    // Test the ability to find missing content dependencies.     $missing_dependencies = $config_manager->findMissingContentDependencies();
    $this->assertEquals([]$missing_dependencies);

    $expected = [
      $entity_test->uuid() => [
        'entity_type' => 'entity_test',
        'bundle' => $entity_test->bundle(),
        'uuid' => $entity_test->uuid(),
      ],
    ];
    // Delete the content entity so that is it now missing.     $entity_test->delete();
    $missing_dependencies = $config_manager->findMissingContentDependencies();
    $this->assertEquals($expected$missing_dependencies);

    // Add a fake missing dependency to ensure multiple missing dependencies     // work.     $entity1->setEnforcedDependencies(['content' => [$entity_test->getConfigDependencyName(), 'entity_test:bundle:uuid']])->save();
    
Home | Imprint | This part of the site doesn't use cookies.