3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 |
9 +--------------------------------------------------------------------+
13 * This api exposes CiviCRM custom field.
15 * @package CiviCRM_APIv3
19 * Create a 'custom field' within a custom field group.
21 * We also empty the static var in the getfields
22 * function after deletion so that the field is available for us (getfields
23 * manages date conversion among other things
25 * @param array $params
26 * Array per getfields metadata.
30 * @throws \CiviCRM_API3_Exception
32 function civicrm_api3_custom_field_create(array $params): array {
34 // Legacy handling for old way of naming serialized fields
35 if (!empty($params['html_type'])) {
36 if ($params['html_type'] === 'CheckBox' ||
strpos($params['html_type'], 'Multi-') === 0) {
37 $params['serialize'] = 1;
39 $params['html_type'] = str_replace(['Multi-Select', 'Select Country', 'Select State/Province'], 'Select', $params['html_type']);
42 // Array created for passing options in params.
43 if (isset($params['option_values']) && is_array($params['option_values'])) {
45 foreach ($params['option_values'] as $key => $value) {
46 // Translate simple key/value pairs into full-blown option values
47 if (!is_array($value)) {
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'];
63 // Legacy handling for historical apiv3 behaviour.
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;
75 $customField = CRM_Core_BAO_CustomField
::create($params);
76 _civicrm_api3_object_to_array_unique_fields($customField, $values[$customField->id
]);
77 _civicrm_api3_custom_field_flush_static_caches();
78 return civicrm_api3_create_success($values, $params, 'CustomField', $customField);
82 * Flush static caches in functions that might have stored available custom fields.
84 function _civicrm_api3_custom_field_flush_static_caches() {
85 if (isset(\Civi
::$statics['CRM_Core_BAO_OptionGroup']['titles_by_name'])) {
86 unset(\Civi
::$statics['CRM_Core_BAO_OptionGroup']['titles_by_name']);
88 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
89 CRM_Core_BAO_UFField
::getAvailableFieldsFlat(TRUE);
93 * Adjust Metadata for Create action.
95 * @param array $params
96 * Array of parameters determined by getfields.
98 function _civicrm_api3_custom_field_create_spec(&$params) {
99 $params['label']['api.required'] = 1;
100 $params['custom_group_id']['api.required'] = 1;
101 $params['is_active']['api.default'] = 1;
102 $params['option_values'] = [
103 'title' => 'Option Values',
104 'description' => "Pass an array of options (value => label) to create this field's option values",
106 $params['data_type']['api.default'] = 'String';
107 $params['is_active']['api.default'] = 1;
111 * Use this API to delete an existing custom field.
113 * @param array $params
114 * Array id of the field to be deleted.
118 function civicrm_api3_custom_field_delete($params) {
119 $field = new CRM_Core_BAO_CustomField();
120 $field->id
= $params['id'];
122 $customFieldDelete = CRM_Core_BAO_CustomField
::deleteField($field);
123 civicrm_api('CustomField', 'getfields', ['version' => 3, 'cache_clear' => 1]);
124 return $customFieldDelete ?
civicrm_api3_create_error('Error while deleting custom field') : civicrm_api3_create_success();
128 * Use this API to get existing custom fields.
130 * @param array $params
131 * Array to search on.
135 function civicrm_api3_custom_field_get($params) {
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']));
142 if (!in_array('serialize', $params['return'])) {
143 $params['return'][] = 'serialize';
145 if (!in_array('data_type', $params['return'])) {
146 $params['return'][] = 'data_type';
150 'Select State/Province' => 'StateProvince',
151 'Select Country' => 'Country',
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;
160 elseif (!in_array($params['html_type'], $serializedTypes)) {
161 $params['serialize'] = 0;
163 if (isset($legacyDataTypes[$params['html_type']])) {
164 $params['data_type'] = $legacyDataTypes[$params['html_type']];
165 unset($params['html_type']);
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) {
172 return str_replace(['Multi-Select', 'Select Country', 'Select State/Province'], 'Select', $val);
173 }, $params['html_type']['IN']);
174 if ($excludeNonSerialized) {
175 $params['serialize'] = 1;
177 if ($onlyNonSerialized) {
178 $params['serialize'] = 0;
183 $results = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
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);
191 if (!empty($result['serialize']) && $result['html_type'] !== 'Autocomplete-Select') {
192 $result['html_type'] = str_replace('Select', 'Multi-Select', $result['html_type']);
202 * Helper function to validate custom field value.
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
212 * @param array $errors
213 * Collect validation errors.
217 * @todo remove this function - not in use but need to review functionality before
218 * removing as it might be useful in wrapper layer
220 function _civicrm_api3_custom_field_validate_field($fieldName, $value, $fieldDetails, &$errors = []) {
227 $dataType = $fieldDetails['data_type'];
228 $htmlType = $fieldDetails['html_type'];
232 if (!CRM_Utils_Rule
::integer($value)) {
233 $errors[$fieldName] = 'Invalid integer value for ' . $fieldName;
238 if (!CRM_Utils_Rule
::numeric($value)) {
239 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
244 if (!CRM_Utils_Rule
::money($value)) {
245 $errors[$fieldName] = 'Invalid numeric value for ' . $fieldName;
250 if (!CRM_Utils_Rule
::url($value)) {
251 $errors[$fieldName] = 'Invalid link for ' . $fieldName;
256 if ($value != '1' && $value != '0') {
257 $errors[$fieldName] = 'Invalid boolean (use 1 or 0) value for ' . $fieldName;
265 if ($htmlType != 'Multi-Select Country' && is_array($value)) {
266 $errors[$fieldName] = 'Invalid country for ' . $fieldName;
270 if (!is_array($value)) {
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;
280 case 'StateProvince':
285 if ($htmlType != 'Multi-Select State/Province' && is_array($value)) {
286 $errors[$fieldName] = 'Invalid State/Province for ' . $fieldName;
290 if (!is_array($value)) {
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;
303 case 'ContactReference':
308 if (in_array($htmlType, ['Select', 'Multi-Select', 'CheckBox', 'Radio'])
309 && !isset($errors[$fieldName])
311 $options = CRM_Core_OptionGroup
::valuesByID($fieldDetails['option_group_id']);
312 if (!is_array($value)) {
316 $invalidOptions = array_diff($value, array_keys($options));
317 if (!empty($invalidOptions)) {
318 $errors[$fieldName] = "Invalid option(s) for field '{$fieldName}': " . implode(',', $invalidOptions);
326 * CRM-15191 - Hack to ensure the cache gets cleared after updating a custom field.
328 * @param array $params
329 * Array per getfields metadata.
333 function civicrm_api3_custom_field_setvalue($params) {
334 require_once 'api/v3/Generic/Setvalue.php';
335 $result = civicrm_api3_generic_setValue(["entity" => 'CustomField', 'params' => $params]);
336 if (empty($result['is_error'])) {
337 CRM_Utils_System
::flushCache();