+--------------------------------------------------------------------+
| CiviCRM version 5 |
+--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2017 |
+ | Copyright CiviCRM LLC (c) 2004-2019 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
*/
function _civicrm_api3_entity_tag_common($params, $op = 'add') {
- $entityIDs = array();
+ $entityIDs = $tagIDs = array();
$entityTable = 'civicrm_contact';
if (is_array($params)) {
foreach ($params as $n => $v) {
$entityIDs[] = $v;
}
elseif (substr($n, 0, 6) == 'tag_id') {
- $tagIDs[] = $v;
+ if (is_array($v)) {
+ $tagIDs = array_merge($tagIDs, $v);
+ }
+ else {
+ $tagIDs[] = $v;
+ }
}
elseif (substr($n, 0, 12) == 'entity_table') {
$entityTable = $v;
}
return $values;
}
+
+/**
+ * Replace tags for an entity
+ */
+function civicrm_api3_entity_tag_replace($params) {
+ $transaction = new CRM_Core_Transaction();
+ try {
+
+ $baseParams = _civicrm_api3_generic_replace_base_params($params);
+ unset($baseParams['tag_id']);
+
+ // Lookup pre-existing records
+ $preexisting = civicrm_api3('entity_tag', 'get', $baseParams);
+ $preexisting = array_column($preexisting['values'], 'tag_id');
+ $toAdd = isset($params['tag_id']) ? $params['tag_id'] : array_column($params['values'], 'tag_id');
+ $toRemove = array_diff($preexisting, $toAdd);
+
+ $result = [];
+ if ($toAdd) {
+ $result = _civicrm_api3_entity_tag_common(array_merge($baseParams, ['tag_id' => $toAdd]), 'add');
+ }
+ if ($toRemove) {
+ $result += _civicrm_api3_entity_tag_common(array_merge($baseParams, ['tag_id' => $toRemove]), 'remove');
+ }
+ // Not really errors
+ unset($result['is_error'], $result['error_message']);
+
+ return civicrm_api3_create_success($result, $params, 'EntityTag', 'replace');
+ }
+ catch(Exception $e) {
+ $transaction->rollback();
+ return civicrm_api3_create_error($e->getMessage());
+ }
+}