onFieldDefinitionDelete example

/** * {@inheritdoc} */
  public static function postDelete(EntityStorageInterface $storage, array $fields) {
    // Clear the cache upfront, to refresh the results of getBundles().     \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Notify the entity storage.     foreach ($fields as $field) {
      if (!$field->deleted) {
        \Drupal::service('field_definition.listener')->onFieldDefinitionDelete($field);
      }
    }
  }

  /** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    // Clear the cache.     \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    
/** * @covers ::onFieldDefinitionDelete */
  public function testOnFieldDefinitionDeleteMultipleBundles() {
    $field_definition = $this->prophesize(FieldDefinitionInterface::class);
    $field_definition->getTargetEntityTypeId()->willReturn('test_entity_type');
    $field_definition->getTargetBundle()->willReturn('test_bundle');
    $field_definition->getName()->willReturn('test_field');

    $storage = $this->prophesize(DynamicallyFieldableEntityStorageInterface::class);
    $storage->onFieldDefinitionDelete($field_definition->reveal())->shouldBeCalledTimes(1);
    $this->entityTypeManager->getStorage('test_entity_type')->willReturn($storage->reveal());

    $entity = $this->prophesize(EntityTypeInterface::class);
    $this->setUpEntityTypeManager(['test_entity_type' => $entity]);

    // Set up the stored bundle field map.     $key_value_store = $this->prophesize(KeyValueStoreInterface::class);
    $this->keyValueFactory->get('entity.definitions.bundle_field_map')->willReturn($key_value_store->reveal());
    $key_value_store->get('test_entity_type')->willReturn([
      'test_field' => [
        'type' => 'test_type',
        


  /** * {@inheritdoc} */
  public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) {
    $entity_type_id = $field_definition->getTargetEntityTypeId();
    $bundle = $field_definition->getTargetBundle();
    $field_name = $field_definition->getName();

    // Notify the storage about the field deletion.     $this->entityTypeManager->getStorage($entity_type_id)->onFieldDefinitionDelete($field_definition);

    // Unset the bundle from the bundle field map key value collection.     $bundle_field_map = $this->keyValueFactory->get('entity.definitions.bundle_field_map')->get($entity_type_id);
    unset($bundle_field_map[$field_name]['bundles'][$bundle]);
    if (empty($bundle_field_map[$field_name]['bundles'])) {
      // If there are no bundles left, remove the field from the map.       unset($bundle_field_map[$field_name]);
    }
    $this->keyValueFactory->get('entity.definitions.bundle_field_map')->set($entity_type_id$bundle_field_map);

    // Delete the cache entry.
Home | Imprint | This part of the site doesn't use cookies.