Merge pull request #22941 from sunilpawar/batch_copy_radio_clear_value
[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 21 * We also empty the static var in the getfields
2986a716 22 * function after deletion so that the field is available for us (getfields
23 * manages date conversion among other things
6a488035 24 *
16b10e64 25 * @param array $params
2e66abf8 26 * Array per getfields metadata.
6a488035 27 *
d60f50a8
CW
28 * @return array
29 * API success array
2986a716 30 * @throws \CiviCRM_API3_Exception
6a488035 31 */
2986a716 32function civicrm_api3_custom_field_create(array $params): array {
6a488035 33
1fd57e91 34 // Legacy handling for old way of naming serialized fields
a7bcb32d 35 if (!empty($params['html_type'])) {
2986a716 36 if ($params['html_type'] === 'CheckBox' || strpos($params['html_type'], 'Multi-') === 0) {
a7bcb32d
CW
37 $params['serialize'] = 1;
38 }
39 $params['html_type'] = str_replace(['Multi-Select', 'Select Country', 'Select State/Province'], 'Select', $params['html_type']);
1fd57e91
CW
40 }
41
2e66abf8 42 // Array created for passing options in params.
6a488035 43 if (isset($params['option_values']) && is_array($params['option_values'])) {
58eaa092 44 $weight = 0;
6a488035 45 foreach ($params['option_values'] as $key => $value) {
58eaa092
CW
46 // Translate simple key/value pairs into full-blown option values
47 if (!is_array($value)) {
cf8f0fff 48 $value = [
58eaa092
CW
49 'label' => $value,
50 'value' => $key,
51 'is_active' => 1,
52 'weight' => $weight,
cf8f0fff 53 ];
58eaa092
CW
54 $key = $weight++;
55 }
6a488035
TO
56 $params['option_label'][$key] = $value['label'];
57 $params['option_value'][$key] = $value['value'];
58 $params['option_status'][$key] = $value['is_active'];
59 $params['option_weight'][$key] = $value['weight'];
60 }
61 }
2986a716 62 elseif (
63 // Legacy handling for historical apiv3 behaviour.
64 empty($params['id'])
65 && !empty($params['html_type'])
66 && $params['html_type'] !== 'Text'
67 && empty($params['option_group_id'])
68 && empty($params['option_value'])
69 && in_array($params['data_type'] ?? '', ['String', 'Int', 'Float', 'Money'])) {
70 // Trick the BAO into creating an option group even though no option values exist
71 // because that odd behaviour is locked in via a test.
72 $params['option_value'] = 1;
73 }
cf8f0fff 74 $values = [];
6a488035 75 $customField = CRM_Core_BAO_CustomField::create($params);
6a488035 76 _civicrm_api3_object_to_array_unique_fields($customField, $values[$customField->id]);
d674c5f8 77 _civicrm_api3_custom_field_flush_static_caches();
244bbdd8 78 return civicrm_api3_create_success($values, $params, 'CustomField', $customField);
6a488035 79}
11e09c59 80
d674c5f8 81/**
2e66abf8 82 * Flush static caches in functions that might have stored available custom fields.
d674c5f8 83 */
9b873358 84function _civicrm_api3_custom_field_flush_static_caches() {
65d27ad8 85 if (isset(\Civi::$statics['CRM_Core_BAO_OptionGroup']['titles_by_name'])) {
86 unset(\Civi::$statics['CRM_Core_BAO_OptionGroup']['titles_by_name']);
87 }
cf8f0fff 88 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
d674c5f8
E
89 CRM_Core_BAO_UFField::getAvailableFieldsFlat(TRUE);
90}
d60f50a8 91
11e09c59 92/**
0aa0303c 93 * Adjust Metadata for Create action.
1c88e578 94 *
cf470720 95 * @param array $params
b081365f 96 * Array of parameters determined by getfields.
6a488035
TO
97 */
98function _civicrm_api3_custom_field_create_spec(&$params) {
99 $params['label']['api.required'] = 1;
100 $params['custom_group_id']['api.required'] = 1;
d5841dff 101 $params['is_active']['api.default'] = 1;
cf8f0fff 102 $params['option_values'] = [
58eaa092
CW
103 'title' => 'Option Values',
104 'description' => "Pass an array of options (value => label) to create this field's option values",
cf8f0fff 105 ];
33533dfe 106 $params['data_type']['api.default'] = 'String';
4b307b2f 107 $params['is_active']['api.default'] = 1;
6a488035
TO
108}
109
110/**
c28e1768 111 * Use this API to delete an existing custom field.
6a488035 112 *
16b10e64 113 * @param array $params
cf470720 114 * Array id of the field to be deleted.
77b97be7
EM
115 *
116 * @return array
c23f45d3 117 */
6a488035 118function civicrm_api3_custom_field_delete($params) {
6a488035
TO
119 $field = new CRM_Core_BAO_CustomField();
120 $field->id = $params['id'];
121 $field->find(TRUE);
122 $customFieldDelete = CRM_Core_BAO_CustomField::deleteField($field);
cf8f0fff 123 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
6a488035
TO
124 return $customFieldDelete ? civicrm_api3_create_error('Error while deleting custom field') : civicrm_api3_create_success();
125}
126
127/**
128 * Use this API to get existing custom fields.
129 *
cf470720
TO
130 * @param array $params
131 * Array to search on.
77b97be7
EM
132 *
133 * @return array
c23f45d3 134 */
6a488035 135function civicrm_api3_custom_field_get($params) {
49df88a8
CW
136 // Legacy handling for serialize property
137 $handleLegacy = (($params['legacy_html_type'] ?? !isset($params['serialize'])) && CRM_Core_BAO_Domain::isDBVersionAtLeast('5.27.alpha1'));
138 if ($handleLegacy && !empty($params['return'])) {
139 if (!is_array($params['return'])) {
140 $params['return'] = explode(',', str_replace(' ', '', $params['return']));
141 }
142 if (!in_array('serialize', $params['return'])) {
1fd57e91
CW
143 $params['return'][] = 'serialize';
144 }
a7bcb32d
CW
145 if (!in_array('data_type', $params['return'])) {
146 $params['return'][] = 'data_type';
147 }
49df88a8 148 }
a7bcb32d
CW
149 $legacyDataTypes = [
150 'Select State/Province' => 'StateProvince',
151 'Select Country' => 'Country',
152 ];
49df88a8
CW
153 if ($handleLegacy && !empty($params['html_type'])) {
154 $serializedTypes = ['CheckBox', 'Multi-Select', 'Multi-Select Country', 'Multi-Select State/Province'];
155 if (is_string($params['html_type'])) {
156 if (strpos($params['html_type'], 'Multi-Select') === 0) {
157 $params['html_type'] = str_replace('Multi-Select', 'Select', $params['html_type']);
158 $params['serialize'] = 1;
159 }
160 elseif (!in_array($params['html_type'], $serializedTypes)) {
161 $params['serialize'] = 0;
162 }
a7bcb32d
CW
163 if (isset($legacyDataTypes[$params['html_type']])) {
164 $params['data_type'] = $legacyDataTypes[$params['html_type']];
165 unset($params['html_type']);
166 }
49df88a8
CW
167 }
168 elseif (is_array($params['html_type']) && !empty($params['html_type']['IN'])) {
169 $excludeNonSerialized = !array_diff($params['html_type']['IN'], $serializedTypes);
170 $onlyNonSerialized = !array_intersect($params['html_type']['IN'], $serializedTypes);
171 $params['html_type']['IN'] = array_map(function($val) {
a7bcb32d 172 return str_replace(['Multi-Select', 'Select Country', 'Select State/Province'], 'Select', $val);
49df88a8
CW
173 }, $params['html_type']['IN']);
174 if ($excludeNonSerialized) {
175 $params['serialize'] = 1;
176 }
177 if ($onlyNonSerialized) {
178 $params['serialize'] = 0;
179 }
1fd57e91
CW
180 }
181 }
182
183 $results = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
184
a7bcb32d
CW
185 if ($handleLegacy && !empty($results['values']) && is_array($results['values'])) {
186 foreach ($results['values'] as $id => &$result) {
187 if (!empty($result['html_type'])) {
188 if (in_array($result['data_type'], $legacyDataTypes)) {
189 $result['html_type'] = array_search($result['data_type'], $legacyDataTypes);
190 }
f0725b60 191 if (!empty($result['serialize']) && $result['html_type'] !== 'Autocomplete-Select') {
a7bcb32d
CW
192 $result['html_type'] = str_replace('Select', 'Multi-Select', $result['html_type']);
193 }
1fd57e91
CW
194 }
195 }
196 }
197
198 return $results;
6a488035
TO
199}
200
11e09c59 201/**
2e66abf8
EM
202 * Helper function to validate custom field value.
203 *
c490a46a 204 * @deprecated
1c88e578 205 *
cf470720
TO
206 * @param string $fieldName
207 * Custom field name (eg: custom_8 ).
208 * @param mixed $value
209 * Field value to be validate.
210 * @param array $fieldDetails
211 * Field Details.
212 * @param array $errors
213 * Collect validation errors.
77b97be7 214 *
795492f3 215 * @return array|NULL
d60f50a8 216 * Validation errors
6a488035
TO
217 * @todo remove this function - not in use but need to review functionality before
218 * removing as it might be useful in wrapper layer
219 */
cf8f0fff 220function _civicrm_api3_custom_field_validate_field($fieldName, $value, $fieldDetails, &$errors = []) {
795492f3 221 return NULL;
35671d00 222 //see comment block
6a488035
TO
223 if (!$value) {
224 return $errors;
225 }
226
227 $dataType = $fieldDetails['data_type'];
228 $htmlType = $fieldDetails['html_type'];
229
230 switch ($dataType) {
231 case 'Int':
232 if (!CRM_Utils_Rule::integer($value)) {
233 $errors[$fieldName] = 'Invalid integer value for ' . $fieldName;
234 }
235 break;
236
237 case 'Float':
238 if (!CRM_Utils_Rule::numeric($value)) {
239 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
240 }
241 break;
242
243 case 'Money':
244 if (!CRM_Utils_Rule::money($value)) {
245 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
246 }
247 break;
248
249 case 'Link':
250 if (!CRM_Utils_Rule::url($value)) {
251 $errors[$fieldName] = 'Invalid link for ' . $fieldName;
252 }
253 break;
254
255 case 'Boolean':
256 if ($value != '1' && $value != '0') {
257 $errors[$fieldName] = 'Invalid boolean (use 1 or 0) value for ' . $fieldName;
258 }
259 break;
260
261 case 'Country':
262 if (empty($value)) {
263 break;
264 }
265 if ($htmlType != 'Multi-Select Country' && is_array($value)) {
266 $errors[$fieldName] = 'Invalid country for ' . $fieldName;
267 break;
268 }
269
270 if (!is_array($value)) {
cf8f0fff 271 $value = [$value];
6a488035
TO
272 }
273
274 $query = "SELECT count(*) FROM civicrm_country WHERE id IN (" . implode(',', $value) . ")";
275 if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
276 $errors[$fieldName] = 'Invalid country(s) for ' . $fieldName;
277 }
278 break;
279
280 case 'StateProvince':
281 if (empty($value)) {
282 break;
283 }
284
285 if ($htmlType != 'Multi-Select State/Province' && is_array($value)) {
286 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
287 break;
288 }
289
290 if (!is_array($value)) {
cf8f0fff 291 $value = [$value];
6a488035
TO
292 }
293
294 $query = "
1c88e578 295SELECT count(*)
6a488035
TO
296 FROM civicrm_state_province
297 WHERE id IN ('" . implode("','", $value) . "')";
298 if (CRM_Core_DAO::singleValueQuery($query) < count($value)) {
299 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
300 }
301 break;
302
303 case 'ContactReference':
304 //FIX ME
305 break;
306 }
307
7c31ae57
SL
308 if (in_array($htmlType, ['Select', 'Multi-Select', 'CheckBox', 'Radio'])
309 && !isset($errors[$fieldName])
6a488035 310 ) {
6a488035
TO
311 $options = CRM_Core_OptionGroup::valuesByID($fieldDetails['option_group_id']);
312 if (!is_array($value)) {
cf8f0fff 313 $value = [$value];
6a488035
TO
314 }
315
316 $invalidOptions = array_diff($value, array_keys($options));
317 if (!empty($invalidOptions)) {
318 $errors[$fieldName] = "Invalid option(s) for field '{$fieldName}': " . implode(',', $invalidOptions);
319 }
320 }
321
322 return $errors;
323}
324
5322ae12 325/**
2e66abf8
EM
326 * CRM-15191 - Hack to ensure the cache gets cleared after updating a custom field.
327 *
d0997921 328 * @param array $params
2e66abf8
EM
329 * Array per getfields metadata.
330 *
645ee340 331 * @return array
5322ae12
CW
332 */
333function civicrm_api3_custom_field_setvalue($params) {
334 require_once 'api/v3/Generic/Setvalue.php';
cf8f0fff 335 $result = civicrm_api3_generic_setValue(["entity" => 'CustomField', 'params' => $params]);
5322ae12
CW
336 if (empty($result['is_error'])) {
337 CRM_Utils_System::flushCache();
338 }
339 return $result;
340}