EDIT please see edit below
Used to work, before CiviCRM v5.18
Interesting observations
Interesting observations
EDIT
Why this no longer works
Works, if you don't need to use phpunit (so, doesn't really work!)
Then myfixercallback
would do the same work. (Note:However, if you are using this then beware phpunit tests that use transaction interface: your code won't run until the test ends - which is too late!)
However! it seems that CiviCRM - at least from 5.18, possibly earlier, now properly creates default custom data. So this hack is simply not needed any more. Sorry, certainly 5.24.2 does not do this.
API Wrapper solution (tested with 5.24.2)
You can implement an API wrapper, but you need to implement it for both API3 and API4.
function giftaid_civicrm_apiWrappers(&$wrappers, $apiRequest) {
if ($apiRequest['entity'] === 'Contribution' && $apiRequest['action'] === 'create') {
$wrappers[] = new CRM_MyApiWrapperContributionCreate();
}
}
// ... Implement the class ...
class CRM_MyApiWrapperContributionCreate implements API_Wrapper {
public function fromApiInput($apiRequest) {
if ($apiRequest instanceof Civi\Api4\Generic\AbstractAction) {
// APIv4
$params = $apiRequest->getParams();
if (empty($params['id']) && noneOfTheCustomFieldsAreDefinedApi4($apiRequest)) {
$apiRequest->addValue('my_fieldset_name.my_field_name', '');
}
}
if (empty($apiRequest['params']['id']) && noneOfTheCustomFieldsAreDefinedApi3($apiRequest)) {
$apiRequest['params']['custom_1234'] = '';
}
}
return $apiRequest;
}
public function toApiOutput($apiRequest, $result) {
return $result;
}
}
In this example
my_fieldset_name
is the custom fieldset, in whichmy_field_name
is a field that has''
as a default value, and an internal ID of 1234 which explains wherecustom_1234
comes from.Rather than relying on setting a value to
''
you could look up the default value for a field, but if you're doing this for a specific solution you can do it this way to be more efficient.noneOfTheCustomFieldsAreDefinedApi3
needs to scan the params for fields namedcustom_N
whereN
is the known ID value of each of your fields. AndnoneOfTheCustomFieldsAreDefinedApi4
needs to scan the params for keys beginning withmy_fieldset_name.