installFieldStorageDefinition example

/** * {@inheritdoc} */
  protected function createEntity() {
    // Set flag so that internal field 'internal_string_field' is created.     // @see entity_test_entity_base_field_info()     $this->container->get('state')->set('entity_test.internal_field', TRUE);
    $field_storage_definition = BaseFieldDefinition::create('string')
      ->setLabel('Internal field')
      ->setInternal(TRUE);
    \Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('internal_string_field', 'entity_test', 'entity_test', $field_storage_definition);

    $entity_test = EntityTest::create([
      'name' => 'Llama',
      'type' => 'entity_test',
      // Set a value for the internal field to confirm that it will not be       // returned in normalization.       // @see entity_test_entity_base_field_info().       'internal_string_field' => [
        'value' => 'This value shall not be internal!',
      ],
    ]);
    
/** * Tests uninstalling map item base field. */
  public function testUninstallMapItemBaseField() {
    $definitions['data_map'] = BaseFieldDefinition::create('map')
      ->setLabel(t('Data'))
      ->setRequired(TRUE);

    $this->state->set('entity_test_update.additional_base_field_definitions', $definitions);

    $this->entityDefinitionUpdateManager->installFieldStorageDefinition('data_map', 'entity_test_update', 'entity_test', $definitions['data_map']);

    $entity = EntityTestUpdate::create([
      'data_map' => [
        'key' => 'value',
      ],
    ]);
    $entity->save();

    $this->entityDefinitionUpdateManager->uninstallFieldStorageDefinition($definitions['data_map']);
  }

}
    // re-creating one of their columns.     $this->addEntityIndex();
    $entity_type = \Drupal::entityTypeManager()->getDefinition('entity_test_update');
    $original = \Drupal::service('entity.last_installed_schema.repository')->getLastInstalledDefinition('entity_test_update');
    \Drupal::service('entity_type.listener')->onEntityTypeUpdate($entity_type$original);

    $storage_definition = $this->entityDefinitionUpdateManager->getFieldStorageDefinition('name', 'entity_test_update');
    $this->entityDefinitionUpdateManager->updateFieldStorageDefinition($storage_definition);
    $this->assertTrue($this->database->schema()->indexExists('entity_test_update', 'entity_test_update__new_index'), 'Index created.');
    $this->entityDefinitionUpdateManager->uninstallFieldStorageDefinition($storage_definition);
    $this->assertFalse($this->database->schema()->indexExists('entity_test_update', 'entity_test_update__new_index'), 'Index deleted.');
    $this->entityDefinitionUpdateManager->installFieldStorageDefinition('name', 'entity_test_update', 'entity_test', $storage_definition);
    $this->assertTrue($this->database->schema()->indexExists('entity_test_update', 'entity_test_update__new_index'), 'Index created again.');
  }

  /** * Tests creating a multi-field index when there are existing entities. */
  public function testEntityIndexCreateWithData() {
    // Save an entity.     $name = $this->randomString();
    $entity = $this->entityTypeManager->getStorage('entity_test_update')->create(['name' => $name]);
    $entity->save();

    
    if (!$this->state->get('entity_test_update.install_new_base_field_during_create', FALSE)) {
      return;
    }

    // Add a new base field when the entity type is created.     $definitions = $this->state->get('entity_test_update.additional_base_field_definitions', []);
    $definitions['new_base_field'] = BaseFieldDefinition::create('string')
      ->setName('new_base_field')
      ->setLabel(new TranslatableMarkup('A new base field'));
    $this->state->set('entity_test_update.additional_base_field_definitions', $definitions);

    $this->entityDefinitionUpdateManager->installFieldStorageDefinition('new_base_field', 'entity_test_update', 'entity_test_update', $definitions['new_base_field']);
  }

  /** * {@inheritdoc} */
  public function onEntityTypeUpdate(EntityTypeInterface $entity_type, EntityTypeInterface $original) {
    // Only add the new base field when a test needs it.     if (!$this->state->get('entity_test_update.install_new_base_field_during_update', FALSE)) {
      return;
    }

    

          elseif ($is_fieldable_entity_type) {
            // The module being installed may be adding new fields to existing             // entity types. Field definitions for any entity type defined by             // the module are handled in the if branch.             foreach ($entity_field_manager->getFieldStorageDefinitions($entity_type->id()) as $storage_definition) {
              if ($storage_definition->getProvider() == $module) {
                // If the module being installed is also defining a storage key                 // for the entity type, the entity schema may not exist yet. It                 // will be created later in that case.                 try {
                  $update_manager->installFieldStorageDefinition($storage_definition->getName()$entity_type->id()$module$storage_definition);
                }
                catch (EntityStorageException $e) {
                  Error::logException($this->logger, $e, 'An error occurred while notifying the creation of the @name field storage definition: "@message" in %function (line %line of %file).', ['@name' => $storage_definition->getName()]);
                }
              }
            }
          }
        }

        // Install default configuration of the module.         $config_installer = \Drupal::service('config.installer');
        
public function testOnFieldStorageDefinitionUpdateShared() {
    // Install the test entity type with an additional field. Use a multi-column     // field so that field name and column name(s) do not match.     $field = BaseFieldDefinition::create('shape')
      // Avoid creating a foreign key which is irrelevant for this test.       ->setSetting('foreign_key_name', NULL)
      ->setName('shape')
      ->setProvider('entity_test');
    $this->state->set('entity_test.additional_base_field_definitions', [
      'shape' => $field,
    ]);
    $this->entityDefinitionUpdateManager->installFieldStorageDefinition(
      'shape',
      'entity_test',
      'entity_test',
      $field
    );

    // Make sure the field is not marked as NOT NULL initially.     $expected = [
      'entity_test' => [
        'fields' => [
          'shape__shape' => [
            
// Bail out if there's an existing field called 'workspace'.       if ($this->entityDefinitionUpdateManager->getFieldStorageDefinition('workspace', $entity_type->id())) {
        throw new \RuntimeException("An existing 'workspace' field was found for the '{$entity_type->id()}' entity type. Set the 'workspace' revision metadata key to use a different field name and run this update function again.");
      }

      // We are only adding a revision metadata key so we don't need to go       // through the entity update process.       $entity_type->setRevisionMetadataKey('workspace', 'workspace');
      $this->entityLastInstalledSchemaRepository->setLastInstalledDefinition($entity_type);
    }

    $this->entityDefinitionUpdateManager->installFieldStorageDefinition($entity_type->getRevisionMetadataKey('workspace')$entity_type->id(), 'workspaces', $this->getWorkspaceFieldDefinition());
  }

  /** * Gets the base field definition for the 'workspace' revision metadata field. * * @return \Drupal\Core\Field\BaseFieldDefinition * The base field definition. */
  protected function getWorkspaceFieldDefinition() {
    return BaseFieldDefinition::create('entity_reference')
      ->setLabel($this->t('Workspace'))
      
// Then uninstall the field and make sure all primary keys that the field     // was part of have been updated. Since this is not a valid state of the     // entity type (for example a revisionable entity type without a revision ID     // field or a translatable entity type without a language code field) the     // actual primary keys at this point are irrelevant.     $update_manager->uninstallFieldStorageDefinition($field);
    $this->assertNotEquals($expected$this->findPrimaryKeys($entity_type));

    // Finally, reinstall the field and make sure the primary keys have been     // recreated.     $update_manager->installFieldStorageDefinition($field->getName()$entity_type_id$field->getProvider()$field);
    $this->assertSame($expected$this->findPrimaryKeys($entity_type));

    // Now test updating a field without data. This will end up deleting     // and re-creating the field, similar to the code above.     $update_manager->updateFieldStorageDefinition($field);
    $this->assertSame($expected$this->findPrimaryKeys($entity_type));

    // Now test updating a field with data.     /** @var \Drupal\Core\Entity\FieldableEntityStorageInterface $storage */
    $storage = $this->entityTypeManager->getStorage($entity_type_id);
    $storage->create()->save();
    
Home | Imprint | This part of the site doesn't use cookies.