Merge pull request #183 from mlutfy/CRM-12135
[civicrm-core.git] / api / v3 / Generic / Update.php
1 <?php
2 // $Id$
3
4 /**
5 * Update function is basically a hack to get around issues listed in
6 * http://issues.civicrm.org/jira/browse/CRM-12144
7 *
8 * It is not recommended & if update doesn't work & fix does then update will not be fixed
9 *
10 * To do this, perform a 'get' action to load the existing values, then merge in the updates
11 * and call 'create' to save the revised entity.
12 *
13 * @param $apiRequest an array with keys:
14 * - entity: string
15 * - action: string
16 * - version: string
17 * - function: callback (mixed)
18 * - params: array, varies
19 */
20 function civicrm_api3_generic_update($apiRequest) {
21 $errorFnName = 'civicrm_api3_create_error';
22
23 //$key_id = strtolower ($apiRequest['entity'])."_id";
24 $key_id = "id";
25 if (!array_key_exists($key_id, $apiRequest['params'])) {
26 return $errorFnName("Mandatory parameter missing $key_id");
27 }
28 $seek = array($key_id => $apiRequest['params'][$key_id], 'version' => $apiRequest['version']);
29 $existing = civicrm_api($apiRequest['entity'], 'get', $seek);
30 if ($existing['is_error']) {
31 return $existing;
32 }
33 if ($existing['count'] > 1) {
34 return $errorFnName("More than one " . $apiRequest['entity'] . " with id " . $apiRequest['params'][$key_id]);
35 }
36 if ($existing['count'] == 0) {
37 return $errorFnName("No " . $apiRequest['entity'] . " with id " . $apiRequest['params'][$key_id]);
38 }
39
40 $existing = array_pop($existing['values']);
41 $p = array_merge($existing, $apiRequest['params']);
42 return civicrm_api($apiRequest['entity'], 'create', $p);
43 }
44