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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_BAO_OptionValue
extends CRM_Core_DAO_OptionValue
{
20 * Create option value.
22 * Note that the create function calls 'add' but has more business logic.
24 * @param array $params
27 * @return CRM_Core_DAO_OptionValue
28 * @throws \CRM_Core_Exception
30 public static function create($params) {
31 if (empty($params['id'])) {
32 self
::setDefaults($params);
34 return CRM_Core_BAO_OptionValue
::add($params);
38 * Set default Parameters.
39 * This functions sets default parameters if not set:
40 * - name & label are set to each other as required (it might make more sense for one
41 * to be required but this would mean a change to the api level)
42 * - weight & value will be set to their respective option groups next values
43 * if nothing is passed in.
45 * Note this function does not check for presence of $params['id'] so should only be called
46 * if 'id' is not present
48 * @param array $params
50 public static function setDefaults(&$params) {
51 $params['label'] = $params['label'] ??
$params['name'];
52 $params['name'] = $params['name'] ?? CRM_Utils_String
::titleToVar($params['label']);
53 $params['weight'] = $params['weight'] ?? self
::getDefaultWeight($params);
54 $params['value'] = $params['value'] ?? self
::getDefaultValue($params);
58 * Get next available value.
59 * We will take the highest numeric value (or 0 if no numeric values exist)
60 * and add one. The calling function is responsible for any
61 * more complex decision making
63 * @param array $params
67 public static function getDefaultWeight($params) {
68 return (int) CRM_Utils_Weight
::getDefaultWeight('CRM_Core_DAO_OptionValue',
69 ['option_group_id' => $params['option_group_id']]);
73 * Get next available value.
74 * We will take the highest numeric value (or 0 if no numeric values exist)
75 * and add one. The calling function is responsible for any
76 * more complex decision making
77 * @param array $params
79 public static function getDefaultValue($params) {
80 $bao = new CRM_Core_BAO_OptionValue();
81 $bao->option_group_id
= $params['option_group_id'];
82 if (isset($params['domain_id'])) {
83 $bao->domain_id
= $params['domain_id'];
86 $bao->whereAdd("value REGEXP '^[0-9]+$'");
87 $bao->selectAdd('(ROUND(COALESCE(MAX(CONVERT(value, UNSIGNED)),0)) +1) as nextvalue');
89 return $bao->nextvalue
;
93 * Retrieve DB object and copy to defaults array.
95 * @param array $params
96 * Array of criteria values.
97 * @param array $defaults
98 * Array to be populated with found values.
101 * The DAO object, if found.
105 public static function retrieve($params, &$defaults) {
106 return self
::commonRetrieve(self
::class, $params, $defaults);
110 * Update the is_active flag in the db.
113 * Id of the database record.
114 * @param bool $is_active
115 * Value we want to set the is_active field.
118 * true if we found and updated the object, else false
120 public static function setIsActive($id, $is_active) {
121 return CRM_Core_DAO
::setFieldValue('CRM_Core_DAO_OptionValue', $id, 'is_active', $is_active);
125 * Add an Option Value.
127 * @param array $params
128 * Reference array contains the values submitted by the form.
130 * deprecated Reference array contains the id.
132 * @return \CRM_Core_DAO_OptionValue
134 * @throws \CRM_Core_Exception
135 * @throws \CiviCRM_API3_Exception
137 public static function add(&$params, $ids = []) {
138 if (!empty($ids['optionValue']) && empty($params['id'])) {
139 CRM_Core_Error
::deprecatedFunctionWarning('$params[\'id\'] should be set, $ids is deprecated');
141 $id = $params['id'] ??
$ids['optionValue'] ??
NULL;
143 // Update custom field data to reflect the new value
144 if ($id && isset($params['value'])) {
145 CRM_Core_BAO_CustomOption
::updateValue($id, $params['value']);
148 // We need to have option_group_id populated for validation so load if necessary.
149 if (empty($params['option_group_id'])) {
150 $params['option_group_id'] = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue',
151 $id, 'option_group_id', 'id'
154 $groupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionGroup',
155 $params['option_group_id'], 'name', 'id'
158 // action is taken depending upon the mode
159 $optionValue = new CRM_Core_DAO_OptionValue();
160 $optionValue->copyValues($params);
162 $isDomainOptionGroup = CRM_Core_OptionGroup
::isDomainOptionGroup($groupName);
163 // When creating a new option for a group that requires a domain, set default domain
164 if ($isDomainOptionGroup && empty($params['id']) && (empty($params['domain_id']) || CRM_Utils_System
::isNull($params['domain_id']))) {
165 $optionValue->domain_id
= CRM_Core_Config
::domainID();
168 // When setting a default option, unset other options in this group as default
169 // FIXME: The extra CRM_Utils_System::isNull is because the API will pass the string 'null'
170 // FIXME: It would help to make this column NOT NULL DEFAULT 0
171 if (!empty($params['is_default']) && !CRM_Utils_System
::isNull($params['is_default'])) {
172 $query = 'UPDATE civicrm_option_value SET is_default = 0 WHERE option_group_id = %1';
174 // tweak default reset, and allow multiple default within group.
175 if ($resetDefaultFor = CRM_Utils_Array
::value('reset_default_for', $params)) {
176 if (is_array($resetDefaultFor)) {
177 $colName = key($resetDefaultFor);
178 $colVal = $resetDefaultFor[$colName];
179 $query .= " AND ( $colName IN ( $colVal ) )";
183 $p = [1 => [$params['option_group_id'], 'Integer']];
185 // Limit update by domain of option
186 $domain = CRM_Utils_System
::isNull($optionValue->domain_id
) ?
NULL : $optionValue->domain_id
;
187 if (!$domain && $id && $isDomainOptionGroup) {
188 $domain = CRM_Core_DAO
::getFieldValue(__CLASS__
, $id, 'domain_id');
191 $query .= ' AND domain_id = %2';
192 $p[2] = [$domain, 'Integer'];
195 CRM_Core_DAO
::executeQuery($query, $p);
198 $groupsSupportingDuplicateValues = ['languages'];
199 if (!$id && !empty($params['value'])) {
200 $dao = new CRM_Core_DAO_OptionValue();
201 if (!in_array($groupName, $groupsSupportingDuplicateValues)) {
202 $dao->value
= $params['value'];
205 // CRM-21737 languages option group does not use unique values but unique names.
206 $dao->name
= $params['name'];
208 if (CRM_Core_OptionGroup
::isDomainOptionGroup($groupName)) {
209 $dao->domain_id
= $optionValue->domain_id
;
211 $dao->option_group_id
= $params['option_group_id'];
212 if ($dao->find(TRUE)) {
213 throw new CRM_Core_Exception('Value already exists in the database');
217 $optionValue->id
= $id;
218 $optionValue->save();
219 CRM_Core_PseudoConstant
::flush();
221 // Create relationship for payment instrument options
222 if (!empty($params['financial_account_id'])) {
223 $optionName = civicrm_api3('OptionGroup', 'getvalue', [
225 'id' => $params['option_group_id'],
227 // Only create relationship for payment instrument options
228 if ($optionName == 'payment_instrument') {
229 $relationTypeId = civicrm_api3('OptionValue', 'getvalue', [
231 'option_group_id' => 'account_relationship',
232 'name' => 'Asset Account is',
235 'entity_table' => 'civicrm_option_value',
236 'entity_id' => $optionValue->id
,
237 'account_relationship' => $relationTypeId,
238 'financial_account_id' => $params['financial_account_id'],
240 CRM_Financial_BAO_FinancialTypeAccount
::add($params);
247 * Delete Option Value.
249 * @param int $optionValueId
254 public static function del($optionValueId) {
255 $optionValue = new CRM_Core_DAO_OptionValue();
256 $optionValue->id
= $optionValueId;
257 if (!$optionValue->find()) {
260 $hookParams = ['id' => $optionValueId];
261 CRM_Utils_Hook
::pre('delete', 'OptionValue', $optionValueId, $hookParams);
262 if (self
::updateRecords($optionValueId, CRM_Core_Action
::DELETE
)) {
263 CRM_Core_PseudoConstant
::flush();
264 $optionValue->delete();
265 CRM_Utils_Hook
::post('delete', 'OptionValue', $optionValueId, $optionValue);
272 * Retrieve activity type label and description.
274 * @param int $activityTypeId
278 * label and description
280 public static function getActivityTypeDetails($activityTypeId) {
281 $query = "SELECT civicrm_option_value.label, civicrm_option_value.description
282 FROM civicrm_option_value
283 LEFT JOIN civicrm_option_group ON ( civicrm_option_value.option_group_id = civicrm_option_group.id )
284 WHERE civicrm_option_group.name = 'activity_type'
285 AND civicrm_option_value.value = {$activityTypeId} ";
287 $dao = CRM_Core_DAO
::executeQuery($query);
291 return [$dao->label
, $dao->description
];
295 * Get the Option Value title.
298 * Id of Option Value.
304 public static function getTitle($id) {
305 return CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_OptionValue', $id, 'label');
309 * Updates contacts affected by the option value passed.
311 * @param int $optionValueId
312 * The option value id.
314 * The action describing whether prefix/suffix was UPDATED or DELETED.
318 public static function updateRecords(&$optionValueId, $action) {
320 $optionValue = new CRM_Core_DAO_OptionValue();
321 $optionValue->id
= $optionValueId;
322 $optionValue->find(TRUE);
324 $optionGroup = new CRM_Core_DAO_OptionGroup();
325 $optionGroup->id
= $optionValue->option_group_id
;
326 $optionGroup->find(TRUE);
329 $gName = $optionGroup->name
;
331 $value = $optionValue->value
;
333 // get the proper group name & affected field name
334 // todo: this may no longer be needed for individuals - check inputs
336 'gender' => 'gender_id',
337 'individual_prefix' => 'prefix_id',
338 'individual_suffix' => 'suffix_id',
339 'communication_style' => 'communication_style_id',
340 // Not only Individuals -- but the code seems to be generic for all contact types, despite the naming...
342 $contributions = ['payment_instrument' => 'payment_instrument_id'];
343 $activities = ['activity_type' => 'activity_type_id'];
344 $participant = ['participant_role' => 'role_id'];
345 $eventType = ['event_type' => 'event_type_id'];
346 $aclRole = ['acl_role' => 'acl_role_id'];
348 $all = array_merge($individuals, $contributions, $activities, $participant, $eventType, $aclRole);
351 foreach ($all as $name => $id) {
352 if ($gName == $name) {
356 if ($fieldName == '') {
360 if (array_key_exists($gName, $individuals)) {
361 $contactDAO = new CRM_Contact_DAO_Contact();
363 $contactDAO->$fieldName = $value;
366 while ($contactDAO->fetch()) {
367 if ($action == CRM_Core_Action
::DELETE
) {
368 $contact = new CRM_Contact_DAO_Contact();
369 $contact->id
= $contactDAO->id
;
370 $contact->find(TRUE);
372 // make sure dates doesn't get reset
373 $contact->birth_date
= CRM_Utils_Date
::isoToMysql($contact->birth_date
);
374 $contact->deceased_date
= CRM_Utils_Date
::isoToMysql($contact->deceased_date
);
375 $contact->$fieldName = 'NULL';
383 if (array_key_exists($gName, $contributions)) {
384 $contribution = new CRM_Contribute_DAO_Contribution();
385 $contribution->$fieldName = $value;
386 $contribution->find();
387 while ($contribution->fetch()) {
388 if ($action == CRM_Core_Action
::DELETE
) {
389 $contribution->$fieldName = 'NULL';
390 $contribution->save();
396 if (array_key_exists($gName, $activities)) {
397 $activity = new CRM_Activity_DAO_Activity();
398 $activity->$fieldName = $value;
400 while ($activity->fetch()) {
406 //delete participant role, type and event type option value
407 if (array_key_exists($gName, $participant)) {
408 $participantValue = new CRM_Event_DAO_Participant();
409 $participantValue->$fieldName = $value;
410 if ($participantValue->find(TRUE)) {
416 //delete event type option value
417 if (array_key_exists($gName, $eventType)) {
418 $event = new CRM_Event_DAO_Event();
419 $event->$fieldName = $value;
420 if ($event->find(TRUE)) {
426 //delete acl_role option value
427 if (array_key_exists($gName, $aclRole)) {
428 $entityRole = new CRM_ACL_DAO_EntityRole();
429 $entityRole->$fieldName = $value;
431 $aclDAO = new CRM_ACL_DAO_ACL();
432 $aclDAO->entity_id
= $value;
433 if ($entityRole->find(TRUE) ||
$aclDAO->find(TRUE)) {
441 * Updates options values weights.
443 * @param int $opGroupId
444 * @param array $opWeights
445 * Options value , weight pair.
447 public static function updateOptionWeights($opGroupId, $opWeights) {
448 if (!is_array($opWeights) ||
empty($opWeights)) {
452 foreach ($opWeights as $opValue => $opWeight) {
453 $optionValue = new CRM_Core_DAO_OptionValue();
454 $optionValue->option_group_id
= $opGroupId;
455 $optionValue->value
= $opValue;
456 if ($optionValue->find(TRUE)) {
457 $optionValue->weight
= $opWeight;
458 $optionValue->save();
464 * Get the values of all option values given an option group ID. Store in system cache
465 * Does not take any filtering arguments. The object is to avoid hitting the DB and retrieve
468 * @param int $optionGroupID
469 * The option group for which we want the values from.
472 * an array of array of values for this option group
474 public static function getOptionValuesArray($optionGroupID) {
475 // check if we can get the field values from the system cache
476 $cacheKey = "CRM_Core_BAO_OptionValue_OptionGroupID_{$optionGroupID}";
477 $cache = CRM_Utils_Cache
::singleton();
478 $optionValues = $cache->get($cacheKey);
479 if (empty($optionValues)) {
480 $dao = new CRM_Core_DAO_OptionValue();
481 $dao->option_group_id
= $optionGroupID;
482 $dao->orderBy('weight ASC, label ASC');
486 while ($dao->fetch()) {
487 $optionValues[$dao->id
] = [];
488 CRM_Core_DAO
::storeValues($dao, $optionValues[$dao->id
]);
491 $cache->set($cacheKey, $optionValues);
494 return $optionValues;
498 * Get the values of all option values given an option group ID as a key => value pair
499 * Use above cached function to make it super efficient
501 * @param int $optionGroupID
502 * The option group for which we want the values from.
505 * an associative array of label, value pairs
507 public static function getOptionValuesAssocArray($optionGroupID) {
508 $optionValues = self
::getOptionValuesArray($optionGroupID);
511 foreach ($optionValues as $id => $value) {
512 $options[$value['value']] = $value['label'];
518 * Get the values of all option values given an option group Name as a key => value pair
519 * Use above cached function to make it super efficient
521 * @param string $optionGroupName
522 * The option group name for which we want the values from.
525 * an associative array of label, value pairs
527 public static function getOptionValuesAssocArrayFromName($optionGroupName) {
528 $dao = new CRM_Core_DAO_OptionGroup();
529 $dao->name
= $optionGroupName;
531 $dao->selectAdd('id');
533 $optionValues = self
::getOptionValuesArray($dao->id
);
536 foreach ($optionValues as $id => $value) {
537 $options[$value['value']] = $value['label'];
543 * Ensure an option value exists.
545 * This function is intended to be called from the upgrade script to ensure
546 * that an option value exists, without hitting an error if it already exists.
548 * This is sympathetic to sites who might pre-add it.
550 * @param array $params the option value attributes.
551 * @return array the option value attributes.
553 public static function ensureOptionValueExists($params) {
554 $result = civicrm_api3('OptionValue', 'get', [
555 'option_group_id' => $params['option_group_id'],
556 'name' => $params['name'],
557 'return' => ['id', 'value'],
561 if (!$result['count']) {
562 $result = civicrm_api3('OptionValue', 'create', $params);
565 return CRM_Utils_Array
::first($result['values']);