Merge pull request #17282 from agh1/calendar-icons
[civicrm-core.git] / api / v3 / CustomField.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
a30c801b 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
a30c801b
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035
TO
9 +--------------------------------------------------------------------+
10 */
11
12/**
c28e1768 13 * This api exposes CiviCRM custom field.
6a488035
TO
14 *
15 * @package CiviCRM_APIv3
6a488035
TO
16 */
17
6a488035
TO
18/**
19 * Create a 'custom field' within a custom field group.
2e66abf8 20 *
6a488035
TO
21 * We also empty the static var in the getfields
22 * function after deletion so that the field is available for us (getfields manages date conversion
23 * among other things
24 *
16b10e64 25 * @param array $params
2e66abf8 26 * Array per getfields metadata.
6a488035 27 *
d60f50a8
CW
28 * @return array
29 * API success array
6a488035
TO
30 */
31function civicrm_api3_custom_field_create($params) {
32
1fd57e91
CW
33 // Legacy handling for old way of naming serialized fields
34 if (!empty($params['html_type']) && ($params['html_type'] == 'CheckBox' || strpos($params['html_type'], 'Multi-') === 0)) {
35 $params['serialize'] = 1;
36 $params['html_type'] = str_replace('Multi-', '', $params['html_type']);
37 }
38
2e66abf8 39 // Array created for passing options in params.
6a488035 40 if (isset($params['option_values']) && is_array($params['option_values'])) {
58eaa092 41 $weight = 0;
6a488035 42 foreach ($params['option_values'] as $key => $value) {
58eaa092
CW
43 // Translate simple key/value pairs into full-blown option values
44 if (!is_array($value)) {
cf8f0fff 45 $value = [
58eaa092
CW
46 'label' => $value,
47 'value' => $key,
48 'is_active' => 1,
49 'weight' => $weight,
cf8f0fff 50 ];
58eaa092
CW
51 $key = $weight++;
52 }
6a488035
TO
53 $params['option_label'][$key] = $value['label'];
54 $params['option_value'][$key] = $value['value'];
55 $params['option_status'][$key] = $value['is_active'];
56 $params['option_weight'][$key] = $value['weight'];
57 }
58 }
cf8f0fff 59 $values = [];
6a488035 60 $customField = CRM_Core_BAO_CustomField::create($params);
6a488035 61 _civicrm_api3_object_to_array_unique_fields($customField, $values[$customField->id]);
d674c5f8 62 _civicrm_api3_custom_field_flush_static_caches();
244bbdd8 63 return civicrm_api3_create_success($values, $params, 'CustomField', $customField);
6a488035 64}
11e09c59 65
d674c5f8 66/**
2e66abf8 67 * Flush static caches in functions that might have stored available custom fields.
d674c5f8 68 */
9b873358 69function _civicrm_api3_custom_field_flush_static_caches() {
cf8f0fff 70 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
d674c5f8
E
71 CRM_Core_BAO_UFField::getAvailableFieldsFlat(TRUE);
72}
d60f50a8 73
11e09c59 74/**
0aa0303c 75 * Adjust Metadata for Create action.
1c88e578 76 *
cf470720 77 * @param array $params
b081365f 78 * Array of parameters determined by getfields.
6a488035
TO
79 */
80function _civicrm_api3_custom_field_create_spec(&$params) {
81 $params['label']['api.required'] = 1;
82 $params['custom_group_id']['api.required'] = 1;
d5841dff 83 $params['is_active']['api.default'] = 1;
cf8f0fff 84 $params['option_values'] = [
58eaa092
CW
85 'title' => 'Option Values',
86 'description' => "Pass an array of options (value => label) to create this field's option values",
cf8f0fff 87 ];
58eaa092 88 // TODO: Why expose this to the api at all?
cf8f0fff 89 $params['option_type'] = [
b2ed8e73
CW
90 'title' => 'Option Type',
91 'description' => 'This (boolean) field tells the BAO to create an option group for the field if the field type is appropriate',
b958933f 92 'api.default' => 1,
b29e2e8b 93 'type' => CRM_Utils_Type::T_BOOLEAN,
cf8f0fff 94 ];
33533dfe 95 $params['data_type']['api.default'] = 'String';
4b307b2f 96 $params['is_active']['api.default'] = 1;
6a488035
TO
97}
98
99/**
c28e1768 100 * Use this API to delete an existing custom field.
6a488035 101 *
16b10e64 102 * @param array $params
cf470720 103 * Array id of the field to be deleted.
77b97be7
EM
104 *
105 * @return array
c23f45d3 106 */
6a488035 107function civicrm_api3_custom_field_delete($params) {
6a488035
TO
108 $field = new CRM_Core_BAO_CustomField();
109 $field->id = $params['id'];
110 $field->find(TRUE);
111 $customFieldDelete = CRM_Core_BAO_CustomField::deleteField($field);
cf8f0fff 112 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
6a488035
TO
113 return $customFieldDelete ? civicrm_api3_create_error('Error while deleting custom field') : civicrm_api3_create_success();
114}
115
116/**
117 * Use this API to get existing custom fields.
118 *
cf470720
TO
119 * @param array $params
120 * Array to search on.
77b97be7
EM
121 *
122 * @return array
c23f45d3 123 */
6a488035 124function civicrm_api3_custom_field_get($params) {
1fd57e91
CW
125 if (($params['legacy_html_type'] ?? TRUE) && !empty($params['return'])) {
126 if (is_array($params['return'])) {
127 $params['return'][] = 'serialize';
128 }
129 elseif (is_string($params['return'])) {
130 $params['return'] .= ',serialize';
131 }
132 }
133
134 $results = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
135
136 if (($params['legacy_html_type'] ?? TRUE) && !empty($results['values']) && is_array($results['values'])) {
137 foreach ($results['values'] as $id => $result) {
138 if (!empty($result['serialize']) && !empty($result['html_type'])) {
139 $results['values'][$id]['html_type'] = str_replace('Select', 'Multi-Select', $result['html_type']);
140 }
141 }
142 }
143
144 return $results;
6a488035
TO
145}
146
11e09c59 147/**
2e66abf8
EM
148 * Helper function to validate custom field value.
149 *
c490a46a 150 * @deprecated
1c88e578 151 *
cf470720
TO
152 * @param string $fieldName
153 * Custom field name (eg: custom_8 ).
154 * @param mixed $value
155 * Field value to be validate.
156 * @param array $fieldDetails
157 * Field Details.
158 * @param array $errors
159 * Collect validation errors.
77b97be7 160 *
795492f3 161 * @return array|NULL
d60f50a8 162 * Validation errors
6a488035
TO
163 * @todo remove this function - not in use but need to review functionality before
164 * removing as it might be useful in wrapper layer
165 */
cf8f0fff 166function _civicrm_api3_custom_field_validate_field($fieldName, $value, $fieldDetails, &$errors = []) {
795492f3 167 return NULL;
35671d00 168 //see comment block
6a488035
TO
169 if (!$value) {
170 return $errors;
171 }
172
173 $dataType = $fieldDetails['data_type'];
174 $htmlType = $fieldDetails['html_type'];
175
176 switch ($dataType) {
177 case 'Int':
178 if (!CRM_Utils_Rule::integer($value)) {
179 $errors[$fieldName] = 'Invalid integer value for ' . $fieldName;
180 }
181 break;
182
183 case 'Float':
184 if (!CRM_Utils_Rule::numeric($value)) {
185 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
186 }
187 break;
188
189 case 'Money':
190 if (!CRM_Utils_Rule::money($value)) {
191 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
192 }
193 break;
194
195 case 'Link':
196 if (!CRM_Utils_Rule::url($value)) {
197 $errors[$fieldName] = 'Invalid link for ' . $fieldName;
198 }
199 break;
200
201 case 'Boolean':
202 if ($value != '1' && $value != '0') {
203 $errors[$fieldName] = 'Invalid boolean (use 1 or 0) value for ' . $fieldName;
204 }
205 break;
206
207 case 'Country':
208 if (empty($value)) {
209 break;
210 }
211 if ($htmlType != 'Multi-Select Country' && is_array($value)) {
212 $errors[$fieldName] = 'Invalid country for ' . $fieldName;
213 break;
214 }
215
216 if (!is_array($value)) {
cf8f0fff 217 $value = [$value];
6a488035
TO
218 }
219
220 $query = "SELECT count(*) FROM civicrm_country WHERE id IN (" . implode(',', $value) . ")";
221 if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
222 $errors[$fieldName] = 'Invalid country(s) for ' . $fieldName;
223 }
224 break;
225
226 case 'StateProvince':
227 if (empty($value)) {
228 break;
229 }
230
231 if ($htmlType != 'Multi-Select State/Province' && is_array($value)) {
232 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
233 break;
234 }
235
236 if (!is_array($value)) {
cf8f0fff 237 $value = [$value];
6a488035
TO
238 }
239
240 $query = "
1c88e578 241SELECT count(*)
6a488035
TO
242 FROM civicrm_state_province
243 WHERE id IN ('" . implode("','", $value) . "')";
244 if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
245 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
246 }
247 break;
248
249 case 'ContactReference':
250 //FIX ME
251 break;
252 }
253
7c31ae57
SL
254 if (in_array($htmlType, ['Select', 'Multi-Select', 'CheckBox', 'Radio'])
255 && !isset($errors[$fieldName])
6a488035 256 ) {
6a488035
TO
257 $options = CRM_Core_OptionGroup::valuesByID($fieldDetails['option_group_id']);
258 if (!is_array($value)) {
cf8f0fff 259 $value = [$value];
6a488035
TO
260 }
261
262 $invalidOptions = array_diff($value, array_keys($options));
263 if (!empty($invalidOptions)) {
264 $errors[$fieldName] = "Invalid option(s) for field '{$fieldName}': " . implode(',', $invalidOptions);
265 }
266 }
267
268 return $errors;
269}
270
5322ae12 271/**
2e66abf8
EM
272 * CRM-15191 - Hack to ensure the cache gets cleared after updating a custom field.
273 *
d0997921 274 * @param array $params
2e66abf8
EM
275 * Array per getfields metadata.
276 *
645ee340 277 * @return array
5322ae12
CW
278 */
279function civicrm_api3_custom_field_setvalue($params) {
280 require_once 'api/v3/Generic/Setvalue.php';
cf8f0fff 281 $result = civicrm_api3_generic_setValue(["entity" => 'CustomField', 'params' => $params]);
5322ae12
CW
282 if (empty($result['is_error'])) {
283 CRM_Utils_System::flushCache();
284 }
285 return $result;
286}