use Civi\Api4\Service\Schema\Joinable\CustomGroupJoinable;
use Civi\Api4\Utils\FormattingUtil;
use Civi\Api4\Utils\CoreUtil;
+use Civi\Api4\Utils\ReflectionUtils;
/**
* @method string getLanguage()
}
/**
- * Write bao objects as part of a create/update action.
+ * Write bao objects as part of a create/update/save action.
*
* @param array $items
* The records to write to the DB.
* @throws \API_Exception
* @throws \CRM_Core_Exception
*/
- protected function writeObjects(&$items) {
- $baoName = $this->getBaoName();
+ protected function writeObjects($items) {
$updateWeights = FALSE;
-
- // TODO: Opt-in more entities to use the new writeRecords BAO method.
- $functionNames = [
- 'Address' => 'add',
- 'CustomField' => 'writeRecords',
- 'EntityTag' => 'add',
- 'GroupContact' => 'add',
- 'Navigation' => 'writeRecords',
- ];
- $method = $functionNames[$this->getEntityName()] ?? NULL;
- if (!isset($method)) {
- $method = method_exists($baoName, 'create') ? 'create' : (method_exists($baoName, 'add') ? 'add' : 'writeRecords');
- }
-
// Adjust weights for sortable entities
if (in_array('SortableEntity', CoreUtil::getInfoItem($this->getEntityName(), 'type'))) {
$weightField = CoreUtil::getInfoItem($this->getEntityName(), 'order_by');
$this->updateWeight($item);
}
- // Skip individual processing if using writeRecords
- if ($method === 'writeRecords') {
- continue;
- }
$item['check_permissions'] = $this->getCheckPermissions();
+ }
- // For some reason the contact bao requires this
- if ($entityId && $this->getEntityName() === 'Contact') {
- $item['contact_id'] = $entityId;
- }
-
- if ($this->getEntityName() === 'Address') {
- $createResult = $baoName::$method($item, $this->fixAddress);
- }
- else {
- $createResult = $baoName::$method($item);
- }
+ // Ensure array keys start at 0
+ $items = array_values($items);
- if (!$createResult) {
+ foreach ($this->write($items) as $index => $dao) {
+ if (!$dao) {
$errMessage = sprintf('%s write operation failed', $this->getEntityName());
throw new \API_Exception($errMessage);
}
-
- $result[] = $this->baoToArray($createResult, $item);
- \CRM_Utils_API_HTMLInputCoder::singleton()->decodeRows($result);
- }
-
- // Use bulk `writeRecords` method if the BAO doesn't have a create or add method
- // TODO: reverse this from opt-in to opt-out and default to using `writeRecords` for all BAOs
- if ($method === 'writeRecords') {
- $items = array_values($items);
- foreach ($baoName::writeRecords($items) as $i => $createResult) {
- $result[] = $this->baoToArray($createResult, $items[$i]);
- }
+ $result[] = $this->baoToArray($dao, $items[$index]);
}
+ \CRM_Utils_API_HTMLInputCoder::singleton()->decodeRows($result);
FormattingUtil::formatOutputValues($result, $this->entityFields());
return $result;
}
+ /**
+ * Overrideable function to save items using the appropriate BAO function
+ *
+ * @param array[] $items
+ * Items already formatted by self::writeObjects
+ * @return \CRM_Core_DAO[]
+ * Array of saved DAO records
+ */
+ protected function write(array $items) {
+ $saved = [];
+ $baoName = $this->getBaoName();
+
+ $method = method_exists($baoName, 'create') ? 'create' : (method_exists($baoName, 'add') ? 'add' : NULL);
+ // Use BAO create or add method if not deprecated
+ if ($method && !ReflectionUtils::isMethodDeprecated($baoName, $method)) {
+ foreach ($items as $item) {
+ $saved[] = $baoName::$method($item);
+ }
+ }
+ else {
+ $saved = $baoName::writeRecords($items);
+ }
+ return $saved;
+ }
+
/**
* @inheritDoc
*/
* @param array $record
*/
private function resolveFKValues(array &$record): void {
+ // Resolve domain id first
+ uksort($record, function($a, $b) {
+ return substr($a, 0, 9) == 'domain_id' ? -1 : 1;
+ });
foreach ($record as $key => $value) {
- if (substr_count($key, '.') !== 1) {
+ if (!$value || substr_count($key, '.') !== 1) {
continue;
}
[$fieldName, $fkField] = explode('.', $key);
continue;
}
$fkDao = CoreUtil::getBAOFromApiName($field['fk_entity']);
- $record[$fieldName] = \CRM_Core_DAO::getFieldValue($fkDao, $value, 'id', $fkField);
+ // Constrain search to the domain of the current entity
+ $domainConstraint = NULL;
+ if (isset($fkDao::getSupportedFields()['domain_id'])) {
+ if (!empty($record['domain_id'])) {
+ $domainConstraint = $record['domain_id'] === 'current_domain' ? \CRM_Core_Config::domainID() : $record['domain_id'];
+ }
+ elseif (!empty($record['id']) && isset($this->entityFields()['domain_id'])) {
+ $domainConstraint = \CRM_Core_DAO::getFieldValue($this->getBaoName(), $record['id'], 'domain_id');
+ }
+ }
+ if ($domainConstraint) {
+ $fkSearch = new $fkDao();
+ $fkSearch->domain_id = $domainConstraint;
+ $fkSearch->$fkField = $value;
+ $fkSearch->find(TRUE);
+ $record[$fieldName] = $fkSearch->id;
+ }
+ // Simple lookup without all the fuss about domains
+ else {
+ $record[$fieldName] = \CRM_Core_DAO::getFieldValue($fkDao, $value, 'id', $fkField);
+ }
unset($record[$key]);
}
}
continue;
}
- // todo are we sure we don't want to allow setting to NULL? need to test
- if (NULL !== $value) {
+ // Null and empty string are interchangeable as far as the custom bao understands
+ if (NULL === $value) {
+ $value = '';
+ }
- if ($field['suffix']) {
- $options = FormattingUtil::getPseudoconstantList($field, $name, $params, $this->getActionName());
- $value = FormattingUtil::replacePseudoconstant($options, $value, TRUE);
- }
+ if ($field['suffix']) {
+ $options = FormattingUtil::getPseudoconstantList($field, $name, $params, $this->getActionName());
+ $value = FormattingUtil::replacePseudoconstant($options, $value, TRUE);
+ }
- if ($field['html_type'] === 'CheckBox') {
- // this function should be part of a class
- formatCheckBoxField($value, 'custom_' . $field['id'], $this->getEntityName());
- }
+ if ($field['html_type'] === 'CheckBox') {
+ // this function should be part of a class
+ formatCheckBoxField($value, 'custom_' . $field['id'], $this->getEntityName());
+ }
- // Match contact id to strings like "user_contact_id"
- // FIXME handle arrays for multi-value contact reference fields, etc.
- if ($field['data_type'] === 'ContactReference' && is_string($value) && !is_numeric($value)) {
- // FIXME decouple from v3 API
- require_once 'api/v3/utils.php';
- $value = \_civicrm_api3_resolve_contactID($value);
- if ('unknown-user' === $value) {
- throw new \API_Exception("\"{$field['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $field['name'], "type" => "integer"]);
- }
+ // Match contact id to strings like "user_contact_id"
+ // FIXME handle arrays for multi-value contact reference fields, etc.
+ if ($field['data_type'] === 'ContactReference' && is_string($value) && !is_numeric($value)) {
+ // FIXME decouple from v3 API
+ require_once 'api/v3/utils.php';
+ $value = \_civicrm_api3_resolve_contactID($value);
+ if ('unknown-user' === $value) {
+ throw new \API_Exception("\"{$field['name']}\" \"{$value}\" cannot be resolved to a contact ID", 2002, ['error_field' => $field['name'], "type" => "integer"]);
}
-
- \CRM_Core_BAO_CustomField::formatCustomField(
- $field['id'],
- $customParams,
- $value,
- $field['custom_group_id.extends'],
- // todo check when this is needed
- NULL,
- $entityId,
- FALSE,
- $this->getCheckPermissions(),
- TRUE
- );
}
+
+ \CRM_Core_BAO_CustomField::formatCustomField(
+ $field['id'],
+ $customParams,
+ $value,
+ $field['custom_group_id.extends'],
+ // todo check when this is needed
+ NULL,
+ $entityId,
+ FALSE,
+ $this->getCheckPermissions(),
+ TRUE
+ );
}
$params['custom'] = $customParams ?: NULL;