diff --git a/CRM/Core/BAO/CustomField.php b/CRM/Core/BAO/CustomField.php index fd0ee4ffbaf1..7b00a48b9519 100644 --- a/CRM/Core/BAO/CustomField.php +++ b/CRM/Core/BAO/CustomField.php @@ -1005,12 +1005,12 @@ public static function deleteField($field) { //not delete the option group and related option values self::checkOptionGroup($field->option_group_id); } - // next drop the column from the custom value table self::createField($field, 'delete'); $field->delete(); CRM_Core_BAO_UFField::delUFField($field->id); + CRM_Core_BAO_Mapping::removeFieldFromMapping('custom_' . $field->id); CRM_Utils_Weight::correctDuplicateWeights('CRM_Core_DAO_CustomField'); CRM_Utils_Hook::post('delete', 'CustomField', $field->id, $field); diff --git a/CRM/Core/BAO/Mapping.php b/CRM/Core/BAO/Mapping.php index 3c9bf18beaa7..d026cf8df7bc 100644 --- a/CRM/Core/BAO/Mapping.php +++ b/CRM/Core/BAO/Mapping.php @@ -1213,4 +1213,14 @@ public static function saveMappingFields($params, $mappingId) { } } + /** + * Remove references to a specific field from save Mappings + * @param string $fieldName + */ + public static function removeFieldFromMapping($fieldName): void { + $mappingField = new CRM_Core_DAO_MappingField(); + $mappingField->name = $fieldName; + $mappingField->delete(); + } + } diff --git a/tests/phpunit/api/v3/CustomFieldTest.php b/tests/phpunit/api/v3/CustomFieldTest.php index cfa7894fe48d..6ec1b9cee3e3 100644 --- a/tests/phpunit/api/v3/CustomFieldTest.php +++ b/tests/phpunit/api/v3/CustomFieldTest.php @@ -422,6 +422,34 @@ public function testCustomFieldDelete() { $this->assertAPISuccess($result); } + /** + * Check That any associated Mapping Field Entries are also removed. + */ + public function testCustomFieldDeleteWithMappingField() { + $customGroup = $this->customGroupCreate(['extends' => 'Individual', 'title' => 'test_group']); + $customField = $this->customFieldCreate(['custom_group_id' => $customGroup['id']]); + $this->assertNotNull($customField['id']); + $mapping = $this->callAPISuccess('Mapping', 'create', [ + 'name' => 'test mapping', + 'mapping_type_id' => 'Export Contact', + ]); + $mappingField = $this->callAPISuccess('MappingField', 'create', [ + 'mapping_id' => $mapping['id'], + 'name' => 'custom_' . $customField['id'], + 'grouping' => 1, + 'column_number' => 0, + ]); + $mappingFieldCheck = $this->callAPISuccess('MappingField', 'get', ['mapping_id' => $mapping['id']]); + $this->assertCount(1, $mappingFieldCheck['values']); + $params = [ + 'id' => $customField['id'], + ]; + $this->callAPISuccess('custom_field', 'delete', $params); + $mappingFieldCheck = $this->callAPISuccess('MappingField', 'get', ['mapping_id' => $mapping['id']]); + $this->assertCount(0, $mappingFieldCheck['values']); + $this->callAPISuccess('Mapping', 'delete', ['id' => $mapping['id']]); + } + /** * Check for Option Value. */